'How to get the required output in python?
Define class Temperature, whose initializer method accepts temperature in fahrenheit unit. Define a descriptor class Celsius with two methods namely get,which returns temperature in celsius units.set,which allows to change temperature to new value in celsius unit.
Input : 1)t1=Temperature(32) 2)t1.celsius=0
Output: 1)32,0.0 2)32.0,0.0
1st input refers to fahrenheit value and 2nd input refers to celsius value
I have tried to write the code but without success:
class Celsius:
def __init__(self, temp = 0):
self.temp = temp
def to_fahrenheit(self):
return (self.temp * 1.8) + 32
def __get__(self):
return(self.temp)
def __set__(self,temp):
self.temp=temp
desc=property(__get__,__set__)
class Temperature:
def __init__(self,temp=0):
self.fahrenheit=temp
self.celsius=(((self.fahrenheit-32)*5)/9)
c=Celsius()
c.desc=self.celsius
self.fahrenheit=c.to_fahrenheit()
The output I got is 1)32.0 , 0.0 2)32.0 , 0
Please let me if any modification required in the code.
Solution 1:[1]
It looks like you're trying to solve a problem that's trying to teach you about descriptors. Take a look at https://docs.python.org/3.7/howto/descriptor.html for more details.
But all that's needed for the problem you're writing a solution for:
class Celsius:
def __get__(self, obj, objtype):
return ((obj.fahrenheit - 32) * 5) / 9
def __set__(self, obj, celcius):
obj.fahrenheit = ((celcius * 9) / 5) + 32
class Temperature:
celcius = Celsius()
def __init__(self, fahrenheit=0):
self.fahrenheit = fahrenheit
Note a few important differences with your code:
Celciusis instantiated and directly assigned tocelciuson the class, instead of to an attribute on the Temperature instance, as in your case.- The descriptor performs the conversion in both directions, without complication on the
Temperatureclass. - Most of the extra code on your implementation didn't do anything; as a general rule, if you add code to try to solve a problem, don't keep it around if it doesn't solve the problem. Less is more in programming.
Solution 2:[2]
This is working for me
class Celsius:
def __get__(self, instance, owner):
return 5 * (instance.fahrenheit - 32) / 9
def __set__(self, instance, value):
instance.fahrenheit = 32 + 9 * value / 5
class Temperature:
celsius = Celsius()
def __init__(self, initial_f):
self.fahrenheit = initial_f
t = Temperature(32)
print(t.celsius)
print(t.fahrenheit)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Grismar |
| Solution 2 | Koustubh Pawar |
