动态创建类 - Python [英] Dynamically creating classes - Python

查看:132
本文介绍了动态创建类 - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆