I am learning Descriptors in python. I am trying the code , but getting below mentioned Attribute error.
AttributeError: 'celciusDescriptor' object has no attribute '_celciusDescriptor__fahrenheit'
I am trying to get the output as (32,0) which is (Fahrenheit, celcius), by getting the temperature in Fahrenheit.
'''
class celciusDescriptor:
def __get__(self, obj, owner):
tempc = self.__fahrenheit
celcius = (tempc - 32)*(5/9)
return self.celcius
def __set__(self, obj, value):
tempcelc = (value - 32)*(5/9)
return tempcelc
class Temperature:
celcius = celciusDescriptor()
def __init__(self, fahrenheit):
self.fahrenheit = fahrenheit
t1 = Temperature(32)
t1.fahrenheit
t1.celcius
'''
Here is one pattern for doing this (by the way, class names typically start with upper case). There is only a need to keep a Celsius or a Fahrenheit value as one can be computed from the other. In this case I am using a class
CelsiusDescriptor
to keep the Celsius value (even though you construct aTemperature
instance with a Fahrenheit value), since this is the way you have it. I then use ordinary properties for getting and setting the Fahrenheit value. The actual Celsius value is stored in theTemperature
object's internal__dict__
attribute, where its other attributes are normally stored. This descriptor also does type enforcement.Prints: