定义类Temperature,其初始值设定项方法接受华氏单位的温度。 用两个方法定义一个描述符类,即 获取,返回摄氏单位的温度。设置,允许将温度更改为摄氏单位的新值。你知道吗
Input : 1)t1=Temperature(32) 2)t1.celsius=0
Output: 1)32,0.0 2)32.0,0.0
第一个输入是指华氏值,第二个输入是指摄氏值
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
如果需要修改代码,请告诉我。你知道吗
看起来你在试图解决一个问题,这个问题试图教会你关于描述符的知识。更多细节请看https://docs.python.org/3.7/howto/descriptor.html。你知道吗
但你所要解决的问题是:
请注意代码中的几个重要差异:
Celcius
被实例化并直接分配给类上的celcius
,而不是像您的例子那样分配给Temperature实例上的属性。你知道吗Temperature
类上没有复杂化。你知道吗相关问题 更多 >
编程相关推荐