【问题标题】:Python3 @Property.setter and Object has no attributePython3 @Property.setter 和 Object 没有属性
【发布时间】:2013-04-22 16:22:37
【问题描述】:

我正在通过“The Quick Python Book”第二版学习使用 Python 的对象。我正在使用 Python 3

我正在尝试了解@property 以及该属性的设置器。 从第 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

【问题讨论】:

    标签: python object properties python-3.x


    【解决方案1】:

    您已经在__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

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 2020-07-25
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      相关资源
      最近更新 更多