@property
Thu Feb 22 2024 16:29:29 GMT+0000 (Coordinated Universal Time)
Saved by
@aguest
#python
#classes
class Celsius:
def __init__(self, temperature=0):
# This calls the setter method `temperature(self, value)` below
self.temperature = temperature
def to_farenheit(self):
# This calls the getter method (`temperature(self)`) method below
return (self.temperature * 1.8) + 32
@property
def temperature(self):
"""
Getter method for the `temperature` property.
If you create an instance of this class and then refer to the
`temperature` property of that instance then this method will be called.
Example:
t = Celsius(37)
t.temperature <-- this is where this getter method is called
"""
print("Getting value...")
return self._temperature
@temperature.setter
def temperature(self, value):
"""
Setter method for the `temperature` property.
If you create an instance of this class and then assign a value
to the `temperature` property of that instance then this method will be called.
Example:
t = Celsius(37) <-- this is where this setter method is called
t.temperature
"""
print("Setting value...")
if value < -273.15:
raise ValueError("Temperature below -273 is not possible")
self._temperature = value
human = Celsius(37) # Setting value...
print(human.temperature) # Getting value...
print(human.to_farenheit()) # Setting value...
coldest_thing = Celsius(-300) # ValueError
content_copyCOPY
The `@property` decorator makes using getters, setters, and deleters easier.
getter - Used to access the value of an attribute.
setter - Used to set/update the value of an attribute.
deleter - Used to delete the instance of an attribute.
The `@property` decorator is used to wrap methods that will act as getters, setters, or deleters for an attribute.
`@property` is used to define the getter method.
`@<attribute_name>.setter` is used to define the setter method.
`@<attribute_name>.deleter` is used to define the deleter method.
https://www.programiz.com/python-programming/property
Comments