3

「クイックPythonブック」第2版でPythonを使ったオブジェクトについて学んでいます。私はPython 3を使用しています

@property とプロパティのセッターについて学習しようとしています。199ページからchpt 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
4

1 に答える 1

4

メソッド内ですべてのメソッドを定義しました__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)

プロパティは記述子であり、この場合はルックアップの優先順位があるため、機能しません。定義した をt.temp返します。@property

于 2013-04-29T04:43:21.890 に答える