This class example was taken from here.
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)
The idea here is that when we create an instance of Celsius and set the temperature attribute (e.g. foo = Celsus (-1000) ), we want to make sure that the attribute is not less than -273 BEFORE setting the temperature attribute.
I don't understand how it seems to bypass self.temperature = temperature
and go straight to the last line. It seems to me like there are three attributes/properties created here: the Class attribute, temperature
; the Instance attribute, temperature
; and the set_temperature
function which sets the attribute _temperature
.
What I DO understand is that the last line (the assignment statement) must run the code property(get_temperature, set_temperature)
which runs the functions get_temperature
and set_temperature
and intern sets the private attribute/property _temperature
.
Moreover, if I run: foo = Celsius(100)
and then foo.temperature
, how is the result of foo.temperature
coming from temperature = property(get_temperature, set_temperature)
and thus _temperature
AND NOT self.temperature = temperature
? Why even have self.temperature = temperature
if temperature = property(get_temperature, set_temperature)
gets ran every time the foo.temperature
call is made?
More questions...
Why do we have two attributes with the same name (e.g. temperature) and how does the code know to retrieve the value of _temperature
when foo.temperature
is called?
Why do we need private attributes/properties an not just temperature?
How does set_temperature(self, value)
obtain the attribute for parameter value
(e.g. the argument that replaces value
)?
In short, please explain this to me like a three year old since I have only been programming a few months. Thank you in advance!