gpt4 book ai didi

python - 在 Python 中使用描述符没有得到预期的结果

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:23 25 4
gpt4 key购买 nike

我是 Python 新手...正在尝试一些带有描述符的代码并运行下面的代码将华氏温度更改为摄氏温度。但我没有得到确切的结果。有人可以帮忙吗,它是如何工作的?

尝试了以下代码

import sys
import os

class Celsius:
def __get__(self, obj, owner):
return self.celsius

def __set__(self, obj, value):
self.celsius = (value-32)*5/9

class Temperature:
celsius = Celsius()

def __init__(self, f):
self.fahrenheit = f

t1 = Temperature(32)
t1.celsius = 0

if __name__ == "__main__":
t1 = Temperature(int(input()))
print(t1.fahrenheit, t1.celsius)

预期结果:(212, 100.0)(根据公式)实际结果:(212,-17.77777777777778)-17 是如何计算的?

最佳答案

您不应该初始化t1.celsius与 0,而是使用 celsius的设置者位于 Temperature.__init__ :

class Temperature:
celsius = Celsius()

def __init__(self, f):
self.fahrenheit = self.celsius = f

演示:https://repl.it/repls/UsableSunnyConfig

关于python - 在 Python 中使用描述符没有得到预期的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55313769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com