动态创建类 - Python [英] Dynamically creating classes - Python
问题描述
我需要动态创建一个类。为了更详细地说明,我需要动态地创建一个Django的Form类的子类。
通过动态我打算创建一个基于配置提供的类
>我想要一个名为CommentForm 的类,它应该将Form类子类化
类应该有一个属性
....在这种情况下
name = forms.CharField strong>
comment = forms.CharField(widget = forms.Textarea())
有用的提示吗? :)
解决方案您可以通过调用
类型内置,传递适当的参数,如:
CommentForm = type(CommentForm,(Form,),
'name':forms.CharField(),
...
})
b $ b它适用于新式类。我不知道,这是否也将与旧式的课程。
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.
e.g.
I want a class named CommentForm which should subclass the Form class
The class should have a list of chosen attributes
....in this case
name = forms.CharField()
comment = forms.CharField(widget=forms.Textarea())
Any useful tips? :)
解决方案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屋!