Python クラスと記述子がどのように機能するかについて、もう少し理解しようとしています。次のコードがあります。
class Base():
def __init__(self):
self.a = 'base_a'
def get_a(self):
return self._x
def set_a(self,val):
self._x = val
def delete_a(self):
pass
a = property(get_a,set_a,delete_a)
class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def a(self):
return 'derived_a'
t = Derived()
print(t.a)
Python 2.7 で実行すると、
[carl@home tmp-carl]$ python2.7 test.py
base_a
Python 3.3 で実行すると、
[carl@home tmp-carl]$ python3 test.py
Traceback (most recent call last):
File "test.py", line 25, in <module>
t = Derived()
File "test.py", line 18, in __init__
Base.__init__(self)
File "test.py", line 5, in __init__
self.a = 'base_a'
AttributeError: can't set attribute
Python3.3 の動作は理解できたと思います。t は Derived のインスタンスなので、Base::__init__
を検索しt.__dict__['a']
ても見つかりません。に移動しDerived.__dict__['a']
、読み取り専用プロパティとエラーを見つけます。Base.__dict__['a']
読み書き可能になることはありません。
しかし、これが本当なら、なぜ Python2.7 が動作するのか、私にはまったく理解できません。で上書きされたプロパティを完全に無視しているようですDerived
。
誰かが私にこれを説明できますか?