动态创建类 - Python [英] Dynamically creating classes - Python
问题描述
我需要动态创建一个类.为了更详细,我需要动态创建 Django Form
类的子类.
I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form
class.
通过动态"我打算根据用户提供的配置创建一个类.
By "dynamically" I intend to create a class based on configuration provided by a user.
例如
我想要一个名为 CommentForm
的类,它应该是 Form
类的子类.
I want a class named CommentForm
which should subclass the Form
class.
该类应该有一个选定属性的列表.
The class should have a list of chosen attributes.
....在这种情况下
name = forms.CharField()
comment = forms.CharField(widget=forms.Textarea())
<小时>
有什么有用的提示吗?:)
Any useful tips? :)
推荐答案
您可以通过调用内置的 type
来动态创建类,同时传递适当的参数,例如:
You can create classes on the fly by calling the type
built-in, passing appropriate arguments along, like:
CommentForm = type("CommentForm", (Form,), {
'name': forms.CharField(),
...
})
它适用于新式类.我不确定,这是否也适用于旧式类.
It works with new-style classes. I am not sure, whether this would also work with old-style classes.
这篇关于动态创建类 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!