即使在更新后,Python 类仍在使用实例化值

标签 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()

我正在获取值

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/

相关文章:

objective-c - 指定Class类的子类

php - 在 php 中正确使用其他类中的类?

javascript - 编写一个带有方法的类

java - NullPointerException 但编译?

python - Python中的统计计数

python - Pandas ,在日期之间填充前几行之间的平均变化

Python:为什么 unittest assertEqual 在这些列表上抛出错误而不是失败?

python - 修改matplotlib patchcollecton3d数据

java - 如何通过从第一个类调用第二个类的方法来调用第三个类的方法

Python 脚本 - 在本地环境中工作但不在开发服务器上工作