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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter