如何在不单独引用它们的情况下以 Python 方式设置多个属性?下面是我的解决方案。
class Some_Class(object):
def __init__(self):
def init_property1(value): self.prop1 = value
def init_property2(value): self.prop2 = value
self.func_list = [init_property1, init_property2]
@property
def prop1(self):
return 'hey im the first property'
@prop1.setter
def prop1(self, value):
print value
@property
def prop2(self):
return 'hey im the second property'
@prop2.setter
def prop2(self, value):
print value
class Some_Other_Class(object):
def __init__(self):
myvalues = ['1 was set by a nested func','2 was set by a nested func']
some_class= Some_Class()
# now I simply set the properties without dealing with them individually
# this assumes I know how they are ordered (in the list)
# if necessary, I could use a map
for idx, func in enumerate(some_class.func_list):
func(myvalues[idx])
some_class.prop1 = 'actually i want to change the first property later on'
if __name__ == '__main__':
test = Some_Other_Class()
当我有许多属性要使用用户定义的值进行初始化时,这变得很有必要。否则我的代码看起来就像一个单独设置每个属性的巨大列表(非常混乱)。
请注意,许多人在下面有很好的答案,我认为我已经找到了一个很好的解决方案。这是一个重新编辑,主要是为了清楚地说明问题。但是,如果有人有更好的方法,请分享!