我正在学习使用Python的对象,"the Quick Python Book“第二版。我使用的是Python 3
我正在尝试学习@属性以及该属性的setter。从第199页到第15页,它有一个我尝试过的例子,但得到了错误:
>>> class Temparature:
def __init__(self):
self._temp_fahr = 0
@property
def temp(self):
return (self._temp_fahr - 32) * 5/9
@temp.setter
def temp(self, new_temp):
self._temp_fahr = new_temp * 9 / 5 + 32
>>> t.temp
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
t.temp
AttributeError: 'Temparature' object has no attribute 'temp'
>>> 为什么我会得到这个错误?另外,为什么我不能直接使用函数调用和参数来设置实例变量new_temp,如下所示:
t = Temparature()
t.temp(34)而不是
t.temp = 43发布于 2013-04-29 12:43:22
您已经在__init__方法中定义了所有方法!只需像这样取消缩进:
class Temparature:
def __init__(self):
self._temp_fahr = 0
@property
def temp(self):
return (self._temp_fahr - 32) * 5/9
@temp.setter
def temp(self, new_temp):
self._temp_fahr = new_temp * 9 / 5 + 32这
t.temp(34)不起作用,因为属性是descriptors,并且在本例中它们具有查找优先级,因此t.temp返回您定义的@property。
https://stackoverflow.com/questions/16271245
复制相似问题