我有一个类,我希望在数据属性发生变化时验证数据。我希望将有效选项存储为setter可以引用的类变量,但我似乎发现<{1}} 选项中的我无法引用任何所有类变量。
为什么?
代码示例:
@var.setter
输出:
class Standard():
def __init__(self):
self.variable1 = 1
self.variable2 = 2
@property
def variable1(self):
# This works
print(self.variable2)
return self.__variable1
@variable1.setter
def variable1(self, var):
# This doesn't work
print(self.variable2)
self.__variable1 = var
x = Standard()
print(x.variable1)
x.variable1 = 4
print(x.variable1)
当它明显的时候。
答案 0 :(得分:4)
您在variable1
中第一次设置__init__
:
def __init__(self):
self.variable1 = 1
self.variable2 = 2
由于self.variable1
处理@variable1.setter
,因此当时variable2
尚不存在。您可以交换这两行:
def __init__(self):
self.variable2 = 2
self.variable1 = 1
现在variable2
在variable1.setter
运行之前已正确设置。
或者,给variable2
一个class属性作为默认值:
class Standard():
# ...
variable2 = 'class default'
@variable1.setter
def variable1(self, var):
print(self.variable2)
self.__variable1 = var
或在getattr()
上使用self
:
@variable1.setter
def variable1(self, var):
print(getattr(self, 'variable2', 'not available yet'))
self.__variable1 = var
或直接设置__variable1
,绕过setter:
class Standard():
def __init__(self):
self.__variable1 = 1 # don't use the setter
self.variable2 = 2