简体   繁体   中英

Using Python @property without setter

The code is from this programiz tutorial .

This is the code, removing some lines for cleaner view:

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

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

    @temperature.setter
    def temperature(self, value):
        print("Setting value...")
        self._temperature = value


human = Celsius(37)
print(human.temperature)
human.temperature = 40

and its output:

Setting value...
Getting value...
37
Setting value...

However, if I comment out the @temperature.setter decorator, the output is just one line:

37

Why isn't the Getting value... line printed?

This is because the "Descriptor".

If you have @setter then the property is a "data descriptor". If you do not have @setter then the property is a "non-data descriptor".

When you call a property from instance. The order the was called is "data descriptor>instance dictionary>non-data descriptor".

So it will call the property in

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

It will not step into temperature funcion.

By the way, you should check about this https://docs.python.org/3/howto/descriptor.html

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