Hands-On Guide to Python Descriptors
Table of Content:
1. Descriptors
1. Define the class Temperature where the initializer method accepts temperature in Fahrenheit units.
2. Define a Descriptor class Celsius with two methods: • __get__- Returns temperature in celsius units.
• __set__- Allows to change temperature to a new value in celsius units.
3. Create an attribute celsius for the Temperature class and try the following code:
t1= Temperature (32)
t1.celsius = 0
Hint: The implementation is provided in the validations. Test against the custom input to validate the output.
4. Use the Test against custom input box to output the result for debugging.
5. Provide 2 numbers in 2 lines (refer test case samples) and click Run Code to display the output/error. • 1st input - Fahrenheit value
⚫ 2nd input - Celsius value
Note: In both cases, Fahrenheit and Celsius is calculated.
Solution
#!/bin/python3 import sys import os # Add Celsius class implementation below. class Celsius: def __get__(self, instance, owner): return (instance.fahrenheit - 32) * 5/9 def __set__(self, instance, value): instance.fahrenheit = (value * 9/5) + 32 # Add temperature class implementation below. class Temperature: celsius = Celsius() def __init__(self, fahrenheit): self.fahrenheit = fahrenheit '''Check the Tail section for input/output''' if __name__ == "__main__": with open(os.environ['OUTPUT_PATH'], 'w') as fout: res_lst = list() t1 = Temperature(int(input())) res_lst.append((t1.fahrenheit, t1.celsius)) t1.celsius = int(input()) res_lst.append((t1.fahrenheit, t1.celsius)) fout.write("{}\n{}".format(*res_lst))