python - 属性(property)没有按预期工作

标签 python

我正在尝试学习关于 http://www.programiz.com/python-programming/property 的教程,并编写了以下脚本:

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def get_temperature(self):
        print("Getting value")
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

    temperature = property(get_temperature, set_temperature)


c = Celsius()

print c.temperature
c.temperature = 100
print c.temperature

当我运行脚本时,我只看到两个温度值:

0
100

但是,我希望 Getting valueSetting value 打印语句也可见。 属性 是否无法正常工作?

最佳答案

您尝试做的事情只适用于新型类(class)。要在 Python 2 中声明一个新式类,你需要有

class Celsius(object):

代替

class Celsius:

在 Python 3 中,所有类都是新式的,所以普通的 class Celsius 工作正常。

关于python - 属性(property)没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851062/

相关文章:

python - 如何使用 django 列表中的信息填充 html 表

python - 如何使用 Python LDAP 获得比服务器大小限制更多的搜索结果?

javascript - 如何在 javascript 部分使用 django 模板变量?

python - 当我的代码对输入进行排序时,为什么它在某些情况下不起作用?

使用二进制 'switch' 进行迭代和/或枚举的 Pythonic 方法

python:可以创建 3 个子图(在两个轴上)吗?

python - 正在读取<内容:encoded> tags using BeautifulSoup 4

python - Django/MySql 不尊重 unique_together

python - 是否有可能在 Python 中用二进制运算符覆盖一元运算符?

python - 元素移动日常采集数据库设计系统问题