Type conversion issue while using Descriptor in Python3 - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Type conversion issue while using Descriptor in Python3 (/thread-26615.html) |
Type conversion issue while using Descriptor in Python3 - mailnsuresh - May-07-2020 This is a little tricky one. Needs more attention since it is a minute thing. There are two classes in the given code. 'celsius' attribute of temperature is handled by 'Celsius' descriptor. Requirement is to have temperature maintained in both fahrenheit and celsius. When executed the code below, as per my understanding, the output should be 32 0.0 32.0 0.0 but the one we get is 32 0.0 32 0.0 Can anyone help me understand why the fahrenheit value in the second line is still an 'int' eventhough it is converted into 'float' in the __set__ method in the descriptor class? #!/bin/python3 import sys import os class Celsius(): def __get__(self, instance, owner): return float(self.__celsius) def __set__(self, instance, value): self.__celsius = value self.__fahrenheit = float(value * 9/5 + 32) class Temperature(): celsius=Celsius() def __init__(self,fahrenheit): self.fahrenheit=fahrenheit self.celsius=(fahrenheit-32)*(5/9) t1 = Temperature(32)[size=medium][/size] print(t1.fahrenheit, t1.celsius) t1.celsius=0 print(t1.fahrenheit, t1.celsius) RE: Type conversion issue while using Descriptor in Python3 - deanhystad - May-07-2020 This should point out the problem. You are not seeing Celsius.__Fahrenheit t1.celsius=10 print(t1.fahrenheit, t1.celsius)
class Temperature(): def __init__(self, fahrenheit): self.__fahrenheit = fahrenheit @property def celsius(self): return (self.__fahrenheit - 32) * 5/9 @celsius.setter def celsius(self, value): self.__fahrenheit = value * 9/5 + 32 @property def fahrenheit(self): return self.__fahrenheit @fahrenheit.setter def fahrenheit(self, value): self.__fahrenheit = float(value) t1 = Temperature(32) print(t1.fahrenheit, t1.celsius) t1.celsius=10 print(t1.fahrenheit, t1.celsius) |