简体   繁体   中英

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

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 .

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. The example works if you make a new-style class with:

class Celsius(object):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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