Solution: Creating Descriptors
Get an overview of the solution on creating descriptors.
We'll cover the following...
Solution overview
We implement TemperatureDescriptor
in the following manner:
Press + to interact
# Creating the descriptor classclass TemperatureDescriptor:# Defining the __get__ method of the descriptor protocoldef __get__(self, obj: object, type = None) -> object:return obj._celsius# Defining the __set__ method of the descriptor protocoldef __set__(self, obj: object, value) -> None:# Raising ValueError if value is not a float or an intif not (type(value) == int or type(value) == float):raise ValueError("Value should be an integar or float")# Setting the valueobj._celsius = value# Defining the __delete__ method of the descriptor protocoldef __delete__(self, obj: object) -> None:del obj._celsiusclass Temperature:celsius = TemperatureDescriptor()def __init__(self):self._celsius = 0# Defining toFahrenheit()# used to convert temperature from celsius to fahrenheitdef toFahrenheit(self):return (self._celsius * 9/5) + 32if __name__ == "__main__":temperature = Temperature()temperature.celsius = 23 # Setting the valueprint(f"Celsius: {temperature.celsius}") # Getting the valueprint(f"Fahrenheit: {temperature.toFahrenheit()}") # Converting to fahrenheitdel temperature # Deleting the value
Code explanation
On lines 2–17 ...