简体   繁体   English

Python-从列表生成对象的属性

[英]Python - generate attributes of an object from a list

I wish to generate an object from a list of properties in such a way: 我希望以这种方式从属性列表中生成一个对象:

class MyClass(MyBaseClass):
    __properties__ = ['property', 'nice_property', 'another_one']

    def __init__(self):
        MyBaseClass.__init__(self)

print(MyClass().property) #prints some default value

Probably I can add all of properties in a init of a base class. 可能我可以在基类的init中添加所有属性。 But then I have to execute it in each of subclasses. 但是然后我必须在每个子类中执行它。 Can I avoid that? 我可以避免吗?

I think what you want to do is to set class attributes, like this: 我认为您想要设置的是类属性,如下所示:

class MyBaseClass(object):
    property = 'default'
    nice_prop = 'default'
    tralala = 'default'

All subclasses of MyBaseClass will have access to the properties. MyBaseClass的所有子类都可以访问属性。 And the objects created from that class and subclasses. 以及从该类和子类创建的对象。 If you overwrite at object level any class property, it will be changed only for that object. 如果在对象级别覆盖任何类属性,则将仅对该对象进行更改。

class SubClass(MyBaseClass):
     pass

sub_obj = SubClass()
print sub_obj.property # prints 'default'
sub_obj.property = 'new value'
print sub_obj.property  # prints new value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM