5

我有一个具有一些属性的类。我想存储此类实例的属性列表,如下所示:

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

以这样的方式

prop_list[0] = something

将调用属性设置器(当然不一定使用相同的语法)。这有可能吗?

4

2 回答 2

3

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
于 2013-06-19T12:33:49.027 回答
1

你可以做:

getter = [ lambda x=x: getattr(obj, x) for x in ['prop1', 'prop2', 'prop3'] ]
setter = [ lambda v, x=x: setattr(obj, x, v) for x in ['prop1', 'prop2', 'prop3'] ]

然后像这样使用它:

getter[0]()

这将返回obj.prop1...的值

同样,您可以使用setter设置新属性:

setter[1]('test')

将创建obj.prop2='test'

于 2013-06-19T12:37:04.680 回答