推荐学习书目
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 · Dec 31, 2015 · 3619 views
    This topic created in 3826 days ago, the information mentioned may be changed or developed.
    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可以吗?

    Supplement 1  ·  Dec 31, 2015
    def create_form(id):
    class_name = 'Form%d' % id
    Test = type(class_name, (NameForm,), {})

    使用 type 搞定
    Supplement 2  ·  Dec 31, 2015
    def create_form(id): 
        class_name = 'Form%d' % id 
        Test = type(class_name, (NameForm,), {})
    
    11 replies    2016-01-01 12:27:12 +08:00
    mengzhuo
        1
    mengzhuo  
       Dec 31, 2015 via iPhone
    metaclass 元编程
    syv2
        2
    syv2  
       Dec 31, 2015
    from copy import deepcopy

    def create_from_class(id):
    klass = deepcopy(NameForm)
    klass.__name__ = str(id)
    return klass
    syv2
        3
    syv2  
       Dec 31, 2015
    我该怎样修改刚才发出去的文本格式。。
    flingjie
        4
    flingjie  
       Dec 31, 2015   ❤️ 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  
       Dec 31, 2015   ❤️ 1
    ```
    from copy import deepcopy

    def create_from_class(id):
    klass = deepcopy(NameForm)
    klass.__name__ = str(id)
    return klass
    ```
    CodingPuppy
        6
    CodingPuppy  
       Dec 31, 2015
    @syv2 哈哈哈
    TheCure
        7
    TheCure  
    OP
       Dec 31, 2015
    def create_form(id):
    class_name = 'Form%d' % id
    Test = type(class_name, (NameForm,), {})

    使用 type 搞定
    syv2
        8
    syv2  
       Dec 31, 2015
    type 的工厂模式确实更高效,学习了!
    lxy42
        9
    lxy42  
       Dec 31, 2015   ❤️ 1
    用 type ,楼上已有例子了,另外可以参考标准库 collections.namedtuple 的实现, namedtuple 就是动态创建的。
    Mark24
        10
    Mark24  
       Dec 31, 2015
    metaClass
    lilindun
        11
    lilindun  
       Jan 1, 2016
    《 fluent python 》 之 metaprogramming
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3101 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 13:24 · PVG 21:24 · LAX 06:24 · JFK 09:24
    ♥ Do have faith in what you're doing.