如何在python中获得所需的输出?

2024-09-30 13:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

定义类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

如果需要修改代码,请告诉我。你知道吗


Tags: to方法self定义def单位温度temp
1条回答
网友
1楼 · 发布于 2024-09-30 13:32:56

看起来你在试图解决一个问题,这个问题试图教会你关于描述符的知识。更多细节请看https://docs.python.org/3.7/howto/descriptor.html。你知道吗

但你所要解决的问题是:

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

请注意代码中的几个重要差异:

  • Celcius被实例化并直接分配给类上的celcius,而不是像您的例子那样分配给Temperature实例上的属性。你知道吗
  • 描述符在两个方向上执行转换,在Temperature类上没有复杂化。你知道吗
  • 实现中的大多数额外代码都没有起到任何作用;一般来说,如果您添加代码是为了解决问题,那么如果它不能解决问题,就不要保留它。编程中少就是多。你知道吗

相关问题 更多 >

    热门问题