简体   繁体   中英

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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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