python代码报错
class TemperaTure:
def __init__(self, hsd=0, ssd=0):
self.hsd = hsd
self.ssd = ssd
self.prompt = 0
def __str__(self):
return self.prompt
__repr__ = __str__
def __setattr__(self, name, value):
if name == 'hsd':
self.__dict__ = value
self.__dict__['ssd'] = (value-32)/1.8
self.prompt = '华氏度为%0.2f\n摄氏度为%0.2f' % (self.hsd, self.ssd)
elif name == 'ssd':
self.__dict__ = value
self.__dict__['hsd'] = value*1.8+32
self.prompt = '摄氏度为%0.2f\n华氏度为%0.2f' % (self.ssd, self.hsd)
else:
return '请正确输入!'
我想知道为什么错,如何修改,请大佬赐教,不胜感激! 改成
self.__dict__['prompt'] = class Temperature:
def __init__(self, C = 0, F = 0, text = None):
self.C = C
self.F = F
self.text = text
def __str__(self):
return self.text
def __setattr__(self, name, value):
if name == "F":
self.__dict__ = value
self.__dict__["C"] = (value - 32)/1.8
elif name == "C":
self.__dict__ = value
self.__dict__["F"] = value*1.8 + 32
else:
print("请正确输入!")
self.__dict__["text"] = "华氏度为: %0.2f\n摄氏度为: %0.2f"%(self.F, self.C)
t = Temperature()
t.C = 37
print(t) class Temperature:
def __init__(self, C = 0, F = 0, text = None):
self.C = C
self.F = F
self.text = text
def __str__(self):
return self.text
def __setattr__(self, name, value):
if name == "F":
self.__dict__ = value
self.__dict__["C"] = (value - 32)/1.8
elif name == "C":
self.__dict__ = value
self.__dict__["F"] = value*1.8 + 32
else:
print("请正确输入!")
self.__dict__["text"] = "华氏度为: %0.2f\n摄氏度为: %0.2f"%(self.F, self.C)
t = Temperature()
t.C = 37
print(t) 本帖最后由 sunyt 于 2021-12-19 19:15 编辑
傻眼貓咪 发表于 2021-12-17 15:56
我想知道为什么
self.prompt = '摄氏度为%0.2f\n华氏度为%0.2f' % (self.ssd, self.hsd)
会报错
而
self.__dict__["text"] = "华氏度为: %0.2f\n摄氏度为: %0.2f"%(self.F, self.C)
是正确的
__str__应该是可以返回字符串的啊 本帖最后由 sunyt 于 2021-12-19 19:14 编辑
【 sunyt 发表于 2021-12-19 19:10
我想知道为什么
会报错
你的报错和 __str__ 没有任何关系,主要是 __setattr__() 你先要了解其用法。
页:
[1]