【发布时间】:2012-07-24 12:06:51
【问题描述】:
如何在不单独引用它们的情况下以 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()
当我有许多属性要使用用户定义的值进行初始化时,这变得很有必要。否则我的代码看起来就像一个单独设置每个属性的巨大列表(非常混乱)。
请注意,很多人在下面都有很好的答案,我认为我已经找到了一个很好的解决方案。这是一个重新编辑,主要是为了清楚地说明问题。但是,如果有人有更好的方法,请分享!
【问题讨论】:
-
您无法确保在 Python 中对类的变量进行只读访问。您只能不鼓励访问这些变量。
-
self.setter1在做什么?如果您在类声明中,那么self将不会是您的类的实例。您能否更清楚地说明这段代码在哪里以及self在这种情况下是什么。 -
另外,您的代码中没有任何属性。
-
你的问题还不是很清楚。 “稍后在代码中单独访问这些功能”是什么意思?在您的示例中,“稍后”在哪里?请张贴一个你想做的例子。
-
-1 因为有一个问题如此乱码,以至于您抱怨每个答案。看看:sscce.org 和 whathaveyoutried.com(很有用,即使你有一些代码)。
标签: python list properties reference setter