我正在运行以下代码:
class testClass:
def __init__(self, left, width):
self.__left = left
self.__width = width
@property
def left(self):
return self.__left
@left.setter
def left(self, newValue):
self.__left = newValue
@property
def width(self):
return self.__width
@width.setter
def width(self, newValue):
self.__width = newValue
def right(self):
return self.__width + self.__left
def rightFixed(self):
return self.width + self.left
test = testClass(10,5)
test.left = 50
print test.right()
print test.rightFixed()
我正在获取值
15
55
谁能解释为什么第一个方法 test.right() 的值是 15,而如果我调用 test.rightFixed() 值,它会给我适当的值?我查看了解释器,代码运行后 _testClass__left 给我 10,而它应该给我 50。@left.setter 属性似乎没有更新 self.__left,而是似乎使它成为自己的副本。
编辑:我还应该注意,我正在运行 2.7.6。正如 Games Brainiac 指出的那样,这在 python 3+ 中运行良好。
最佳答案
将 (object)
添加到您的类中。在 Python 2.6 之后,引入了一个新的数据模型。参见 https://docs.python.org/2/reference/datamodel.html#newstyle .
请参阅 DSM 的评论,了解 Python3 和 Python2 对待它的不同之处。
class testClass(object):
def __init__(self, left, width):
self.__left = left
self.__width = width
@property
def left(self):
return self.__left
@left.setter
def left(self, newValue):
self.__left = newValue
@property
def width(self):
return self.__width
@width.setter
def width(self, newValue):
self.__width = newValue
def right(self):
return self.__width + self.__left
def rightFixed(self):
return self.width + self.left
>>test = testClass(10,5)
>>test.left = 50
>>print test.right()
55
>>print test.rightFixed()
55
关于即使在更新后,Python 类仍在使用实例化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26477812/