Reputation: 1053
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?
Upvotes: 0
Views: 343
Reputation: 1161
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
Upvotes: 1