【发布时间】:2017-05-30 15:30:08
【问题描述】:
在 Python 中,是否可以在其 setter 中访问类变量的当前值?
例如:
# Getter
@property
# ...
# Setter
@position.setter
def position(self, value):
# Do something with current value...
# self.position, self.__position, position and __position don't seem to work
# Update position with the given value
self.__position = value
# Do something with the new value...
C# 中的等价物是:
private Position position;
public Position Position
{
get
{
// ...
}
set
{
// Do something with the current value...
// Update position field with given object
position = value;
// Do something with the new value...
}
}
更新
这是一个最小、完整且可验证的示例,以更好地说明我的问题:
class C:
def __init__(self):
self.x = 2
@property
def x(self):
return self.__x
@x.setter
def x(self, value):
print(self.x)
self.__x = value
print(self.x)
c = C()
抛出以下错误:
AttributeError: 'C' object has no attribute '_C__x'
发生这种情况是因为 setter 尝试在更新变量之前打印变量的当前值,并且当 x 在 __init__ 中设置为 2 时运行 setter,此时 x 之前没有被赋值(没有要打印的当前值)。
【问题讨论】:
-
你是什么意思“似乎不起作用”?在您分配给它之前,
self.__position仍然是旧值,因此self.position也将访问旧值。 -
这就是我的想法,但是尝试在 setter 中访问
self.position或self.__position都会导致以下错误:AttributeError: 'GameObject' object has no attribute '_GameObject__position'。 (GameObject是包含position变量的类。) -
请给minimal reproducible example。还可以考虑放弃
__double_underscore,因为名称修改会不必要地使事情复杂化。 -
在制作MCV示例时,我发现在
__init__中第一次设置变量时抛出了错误,此时变量尚未被赋值。如何检查这种情况? -
@jonrsharpe 关于双下划线,我错误地认为在其设置器中更新类变量的值时需要它们。
标签: python class properties setter