我正在用“快速Python书”第二版学习Python对象。我使用的是python3
我试图了解@property以及属性的setters。 在第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,比如:
^{pr2}$而不是
t.temp = 43
您已经在
__init__
方法中定义了所有方法!就这样不让他们知道:这个
^{pr2}$不起作用,因为属性是descriptors,在本例中它们具有查找优先级,因此
t.temp
返回您定义的@property
。在相关问题 更多 >
编程相关推荐