简体   繁体   English

Python属性不符合预期

[英]Python property does not behave as expected

I am going through the explanations and examples on the below website: 我在下面的网站上浏览解释和示例:

http://www.programiz.com/python-programming/property http://www.programiz.com/python-programming/property

And it seems that the code does not behave as expected when I try it. 而且,当我尝试该代码时,该代码的行为似乎不符合预期。 So what I try to do is to execute the following: 因此,我尝试执行以下操作:

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

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

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

And I would expect the output to be as described on the above-mentioned site: 我希望输出结果如上述站点中所述:

Setting value #That means that "set_temperature" was called by the constructor when the object is being created

However I get no output at all. 但是我根本没有输出。 The program runs with no errors but the screen remains empty. 该程序运行无错误,但屏幕保持空白。 Is there something I am doing wrong? 我做错什么了吗?

Properties only work on new-style classes. 属性仅适用于新式类。 Your Celsius class needs to inherit from object . 您的Celsius类需要从object继承。

Also note that it is much more idiomatic these days to write a property as a decorator: 还要注意,如今将属性写为装饰器是更加惯用的:

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

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

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

Python 2.7 still uses "old-style classes" by default. 默认情况下,Python 2.7仍使用“旧类”。 The example works if you make a new-style class with: 如果您使用以下方法创建新样式的类,则该示例有效:

class Celsius(object):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM