なぜ@foo.セッタPythonでは動作しないでくれますか?
-
11-09-2019 - |
質問
なんで遊んでデコレータのPython2.6で、私も困ってます。ここでは私のクラスファイル:
class testDec:
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
何を思ったこの意味は x
のような物件もこれらの機能を取得し、セットです。そこで、叩いて遊休とを確認する
>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testDec.py", line 18, in x
return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5
明らかに、最初の呼び出して、そのゲッターがあり、デフォルト値で失敗します。OK、良くわかりました。しかし、通話割り当てる t.x = 5
そうを作成し、新規物件の x
, 在のゲッターません。
と思欠?
解決
すう用 定番の古いスタイルの授業 python2.るために 特性 正常に動作を使用する必要があり 新形式クラス 代わりに(python2必要 からの継承 object
).だけを宣言するクラスとして MyClass(object)
:
class testDec(object):
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
この作品:
>>> k = testDec()
>>> k.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/devel/class_test.py", line 6, in x
return self._x
AttributeError: 'testDec' object has no attribute '_x'
>>> k.x = 5
called setter
>>> k.x
called getter
5
>>>
別の詳細を引き起こす可能性のある問題は、両方法が必要に同じ名前の物件です。 設定されていない場合は、セッターと異なる名前のこのように動作しません:
@x.setter
def x_setter(self, value):
...
が切り替わりますので、そのではないので簡単にスポットでは、順:のゲッター が定められている必要がある最初の.設定されていない場合は、セッターの最初き name 'x' is not defined
エラーになります。
他のヒント
この例外を探してここにつまずき、他の人のためだけのノート:両方の機能が同じ名前を持っている必要があります。次のようにメソッドを命名すると、例外が発生します。
@property
def x(self): pass
@x.setter
def x_setter(self, value): pass
の代わりに、両方の方法に同じ名前を付ける
@property
def x(self): pass
@x.setter
def x(self, value): pass
宣言の順序が重要ということに注意することも重要です。ゲッターは、ファイル内のセッター前に定義しなければならないか、または他のあなたがNameError: name 'x' is not defined
を取得します。
あなたがオブジェクトからクラスを派生させて、あなたが新しいスタイルのクラスを使用する必要があります:
class testDec(object):
....
そして、それが動作するはずです。
の場合には誰もが、私は<のhref = "HTTPSに基づいて、クラスの__init__
メソッドからセッターを呼び出すときに、これは細心の注意が必要であることを追加したいと思います上記の回答に加えて、Googleからのここに来る:// stackoverflowの.COM / / 808734分の3942118" >この回答する
具体的に:
class testDec(object):
def __init__(self, value):
print 'We are in __init__'
self.x = value # Will call the setter. Note just x here
#self._x = value # Will not call the setter
@property
def x(self):
print 'called getter'
return self._x # Note the _x here
@x.setter
def x(self, value):
print 'called setter'
self._x = value # Note the _x here
t = testDec(17)
print t.x
Output:
We are in __init__
called setter
called getter
17