即使在更新之后,Python类也在使用实例化的值

1 python class

我正在运行以下代码:

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()
Run Code Online (Sandbox Code Playgroud)

我正在获得价值观

15
55
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么第一个方法test.right()给出值15,而如果我调用test.rightFixed()值它给我适当的值?我已经查看了解释器,并且在代码运行后_testClass__left给了我10,而它应该给我50. @ left.setter属性似乎没有更新self .__ left,而是它似乎正在制作它自己的副本.

编辑:我还应该注意,我正在运行2.7.6.正如Games Brainiac所指出的,这在python 3+中运行良好.

Par*_*ker 5

加入(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
Run Code Online (Sandbox Code Playgroud)