我有一个属性的类.我想存储这个类的实例的属性列表,如下所示:
obj = MyClass()
prop_list = [ obj.prop1,obj.prop2,obj.prop3,obj.prop1,obj.prop3 ]
以这种方式
prop_list[0] = something
最佳答案
存储属性的名称,然后使用setattr:
obj = MyClass()
prop_list = [ "prop1","prop2","prop3","prop1","prop3" ]
setattr(obj,prop_list[0],something)
如果您确实需要项目分配语法,则可以使用自定义类:
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","prop3"])
prop_list[0] = something