Python3@属性.setter物体没有属性

2024-09-27 23:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用“快速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

Tags: 对象selfnew属性initdef错误property
1条回答
网友
1楼 · 发布于 2024-09-27 23:25:12

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

这个

^{pr2}$

不起作用,因为属性是descriptors,在本例中它们具有查找优先级,因此t.temp返回您定义的@property。在

相关问题 更多 >

    热门问题