...

/

Solution: Creating Descriptors

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 class
class TemperatureDescriptor:
# Defining the __get__ method of the descriptor protocol
def __get__(self, obj: object, type = None) -> object:
return obj._celsius
# Defining the __set__ method of the descriptor protocol
def __set__(self, obj: object, value) -> None:
# Raising ValueError if value is not a float or an int
if not (type(value) == int or type(value) == float):
raise ValueError("Value should be an integar or float")
# Setting the value
obj._celsius = value
# Defining the __delete__ method of the descriptor protocol
def __delete__(self, obj: object) -> None:
del obj._celsius
class Temperature:
celsius = TemperatureDescriptor()
def __init__(self):
self._celsius = 0
# Defining toFahrenheit()
# used to convert temperature from celsius to fahrenheit
def toFahrenheit(self):
return (self._celsius * 9/5) + 32
if __name__ == "__main__":
temperature = Temperature()
temperature.celsius = 23 # Setting the value
print(f"Celsius: {temperature.celsius}") # Getting the value
print(f"Fahrenheit: {temperature.toFahrenheit()}") # Converting to fahrenheit
del temperature # Deleting the value

Code explanation

  • On lines 2–17 ...