Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a list of properties (not their values)?

Tags:

python

I have a class with some properties. I would like to store a list of the properties of an instance of this class like so:

obj = MyClass()
prop_list = [ obj.prop1, obj.prop2, obj.prop3, obj.prop1, obj.prop3 ]

in such way that

prop_list[0] = something

would invoke the property setter (not necessarily with the same syntax of course). Is this possible somehow?

like image 999
Tamás Szelei Avatar asked Oct 03 '22 19:10

Tamás Szelei


1 Answers

Store the names of the properties instead and use setattr:

obj = MyClass()
prop_list = [ "prop1", "prop2", "prop3", "prop1", "prop3" ]
setattr(obj, prop_list[0], something)

If you really need the item assignment syntax, this is also possible with a custom class:

class CustomPropertyList(object):
    def __init__(self, obj, names):
        self.obj = obj
        self.property_names = list(names)

    def __getitem__(self, item):
        return getattr(self.obj, self.property_names[item])

    def __setitem__(self, item, value):
        setattr(self.obj, self.property_names[item], value)

prop_list = CustomPropertyList(obj, ["prop1", "prop2", "prop3", "prop1", "prop3"])
prop_list[0] = something
like image 129
Tamás Avatar answered Oct 07 '22 18:10

Tamás