[英]Python3 @Property.setter and Object has no attribute
I am learning about objects with Python with "the Quick Python Book" second edition. 我正在通过“ Quick Python Book”第二版来学习有关Python的对象。 I am using Python 3
我正在使用Python 3
I am trying to learn about the @property along with the setters for the property. 我正在尝试了解@property以及该属性的设置器。 From page 199 chpt 15 it has this example that I tried but I get errors:
从第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'
>>>
Why am I getting this error? 为什么会出现此错误? Also, why couldn't I just set the instance variable new_temp with a function call and parameter like:
另外,为什么我不能只使用函数调用和参数来设置实例变量new_temp:
t = Temparature()
t.temp(34)
instead of 代替
t.temp = 43
You've defined all of your methods inside the __init__
method! 您已经在
__init__
方法中定义了所有方法! Just unindent them like so: 像这样取消缩进:
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
This 这个
t.temp(34)
doesn't work because properties are descriptors and they have lookup precedence in this case so t.temp
returns the @property
that you defined. 不工作,因为性能的描述 ,他们在这种情况下,查找优先,因此
t.temp
返回@property
你定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.