如何pythonical设置多个属性而不单独引用它们?下面是我的解决方案。在
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()
当我有许多属性要用用户定义的值初始化时,这就变得很有必要了。否则,我的代码看起来就像是一个单独设置每个属性的巨大列表(非常混乱)。在
请注意,下面很多人都有很好的答案,我想我已经找到了一个好的解决方案。这是一个重新编辑主要是为了清楚地说明问题。但是,如果有人有更好的方法请分享!在
我。。。最后我想我知道你想做什么,你不需要用你接近它的方式去做。让我试试这个。在
值得指出的是,idx变量和enumerate调用在第二种形式中是多余的,但我不确定您是否需要在其他地方使用它。在
只需使用@property decorator
像这样?在
如果你只想允许设置,那么不要给它一个默认值
^{pr2}$或者如果您只想允许检索,只需命令第二个参数
如果您在对象dict中查找属性,您将得到属性描述符(如果有的话),类也是如此;例如
假设
^{pr2}$descriptor
是一个描述符,它将具有以下方法:注意}。在
fget
和{相关问题 更多 >
编程相关推荐