这就是我正在尝试做的事情:我想编写一个工作 python 类,只需给它一个随机值,它就可以自己转换所有内容。
我想要的是以下内容:
>>> first=Temperature()
>>> first.celsius = 60
>>> first.kelvin
333.15
>>> first.fahrenheit
140
无论我设置的第一个描述符是什么,我都希望其他人自己转换,即使我执行以下操作:
>>> first.celsius = 60
>>> first.kelvin
333.15
>>> first.celsius += 1
>>> first.kelvin
334.15
这是我一直在处理的代码:
class Celsius:
def __get__(self, instance, owner):
return 5 * (instance.fahrenheit - 32) / 9
def __set__(self, instance, value):
instance.fahrenheit = 32 + 9 * value / 5
def __set__(self, instance, value):
instance.kelvin = value + 273.15
class Temperature:
celsius = Celsius()
def __init__(self):
self.fahrenheit = 0
def __init__(self):
self.kelvin = 0
有些事情正在工作,但转换回来的工作并不顺利,并且会出现一些错误,但我真的不知道如何使这项工作,即使你们给我一份 20 页的文档,我也会很感激一些帮助。