V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
TheCure
V2EX  ›  Python

python 如何动态创建一个类?

  •  
  •   TheCure · 2015-12-31 16:29:48 +08:00 · 3060 次点击
    这是一个创建于 3046 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class NameForm(Form):
        name = StringField('What is your name?')
    
        @classmethod
        def append_field(self, name, field):
            setattr(self, name, field)
    

    嗯..我需要动态创建一个新类,要求是,这个类需要继承 NameForm,这个类的名称是可以运行中指定的.就像下面一样

    def create_form_class(id):
        pass
    
    form1 = create_form_class(1)
    
    form2 = create_form_class(2)
    

    这个对象 form1 就是一个类 Form1(NameForm) 的对象,form2 就是类 Form2(NameForm)的对象.

    这个需求用 eval 可以实现,还有其他办法吗?metaclass 可以吗,但是 metaclass 可以定义类的属性,怎么去修改类名?dict可以吗?

    第 1 条附言  ·  2015-12-31 19:37:38 +08:00
    def create_form(id):
    class_name = 'Form%d' % id
    Test = type(class_name, (NameForm,), {})

    使用 type 搞定
    第 2 条附言  ·  2015-12-31 19:38:50 +08:00
    def create_form(id): 
        class_name = 'Form%d' % id 
        Test = type(class_name, (NameForm,), {})
    
    11 条回复    2016-01-01 12:27:12 +08:00
    mengzhuo
        1
    mengzhuo  
       2015-12-31 16:31:59 +08:00 via iPhone
    metaclass 元编程
    syv2
        2
    syv2  
       2015-12-31 16:37:26 +08:00
    from copy import deepcopy

    def create_from_class(id):
    klass = deepcopy(NameForm)
    klass.__name__ = str(id)
    return klass
    syv2
        3
    syv2  
       2015-12-31 16:38:22 +08:00
    我该怎样修改刚才发出去的文本格式。。
    flingjie
        4
    flingjie  
       2015-12-31 16:38:50 +08:00   ❤️ 2
    使用 type 函数.
    def __init__(self, x):
    self.x = x

    def printX(self):
    print self.x

    Test = type('Test', (object,), {'__init__': __init__, 'printX': printX})
    等同于
    class Test(object):
    def __init__(self, x):
    self.x = x

    def printX(self):
    print self.x
    syv2
        5
    syv2  
       2015-12-31 16:40:18 +08:00   ❤️ 1
    ```
    from copy import deepcopy

    def create_from_class(id):
    klass = deepcopy(NameForm)
    klass.__name__ = str(id)
    return klass
    ```
    CodingPuppy
        6
    CodingPuppy  
       2015-12-31 16:44:31 +08:00
    @syv2 哈哈哈
    TheCure
        7
    TheCure  
    OP
       2015-12-31 17:21:44 +08:00
    def create_form(id):
    class_name = 'Form%d' % id
    Test = type(class_name, (NameForm,), {})

    使用 type 搞定
    syv2
        8
    syv2  
       2015-12-31 17:27:45 +08:00
    type 的工厂模式确实更高效,学习了!
    lxy42
        9
    lxy42  
       2015-12-31 17:35:42 +08:00   ❤️ 1
    用 type ,楼上已有例子了,另外可以参考标准库 collections.namedtuple 的实现, namedtuple 就是动态创建的。
    Mark24
        10
    Mark24  
       2015-12-31 20:10:24 +08:00
    metaClass
    lilindun
        11
    lilindun  
       2016-01-01 12:27:12 +08:00
    《 fluent python 》 之 metaprogramming
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2234 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:33 · PVG 23:33 · LAX 08:33 · JFK 11:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.