I'm trying to understand property in depth following this article.
https://www.programiz.com/python-programming/property
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)
One thing that intrigues me is how the _temperature
and temperature
variable works.
As per this article,
The attribute temperature is a property object which provides interface to this private variable.
How does this interface functionality provided in python?
c = Celsius()
print(dir(c))
When I print the dir(c) it shows the following -
['__doc__', '__init__', '__module__', 'get_temperature', 'set_temperature', 'temperature', 'to_fahrenheit']
The _temperature variable is hidden.
When I inherit the Celsius(object)
from object class that shows a different result -
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_temperature', 'get_temperature', 'set_temperature', 'temperature', 'to_fahrenheit']