Property
Property decorator example
root@ubuntu-232:~/deepak/test# cat test.py
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)
temp=Celsius(20)
print(temp.temperature)
root@ubuntu-232:~/deepak/test# python3 test.py
Setting value
Getting value
20
Setter and getter API
Setter and getter
root@ubuntu-232:~/deepak/test# cat test2.py
class P:
def __init__(self,x):
self.x = x
@property
def x(self):
print("Inside property")
return self.__x
@x.setter
def x(self, x):
print("Inside setter")
if x < 0:
self.__x = 0
elif x > 1000:
self.__x = 1000
else:
self.__x = x
p=P(10)
p.x=20
print(p.x)
root@ubuntu-232:~/deepak/test# python3 test2.py
Inside setter
Inside setter
Inside property
20
https://www.programiz.com/python-programming/property
https://www.python-course.eu/python3_properties.php