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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With