I’m hoping to get a clearer understanding of properties and why they can be implemented as decorators, but the naming conventions of examples are making them more confusing than necessary. I attempt removing unnecessary information in my own notebook but hope to see how someone else would teach this. Disambiguating the variable names is top priority for me.
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)
Above is an example from https://www.programiz.com/python-programming/property. What is confusing is the variable
temperature appears 3x and i’m sure they are different things under the hood. First,
__init__, it takes as an input
temperature. My own tests show i can totally delete this input and hardcode a constant and still have property work.
Secondly, there is
self.temperature, then i realized i can totally delete
__init__ and the whole thing still works. So why did the author add these 2
temperature? Is init
self.temperature here important for something later?
Next there is also
_temperature. Can i understand that
self.temperature is a higher level abstraction of
_temperature? So _temperature is used by python interpreter, while temperature is called by user?
Moving on to the decarator implementation:
class Celsius: 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 temperature(self, value): if value < -273: raise ValueError("Temperature below -273 is not possible") print("Setting value") self._temperature = value
__init__, the previous
self.temperature is now
self._temperature. Again this whole
__init__ can be deleted and still have property concept work.
I don’t understand how
temperature = property(get_temperature,set_temperature) can be written as
@property because i thought decorators do
func = decorator(func) (the pattern being it must be assigned back to same name it decorated, which is not the case for property taking 2 inputs and assigning to 1). Also, what is the importance of
@temperature.setter being named exactly that? Why not
@property.setter. Is there some dependence (like 1 must be defined above in the script/ run before in real time) between