サブクラスのプロパティを上書きしようとしたときの動作に少し混乱しています。
Parent
最初の例では、との 2 つのクラスを設定しChild
ます。 Parent
から継承しobject
、からChild
継承しParent
ます。プロパティa
は、プロパティ デコレータを使用して定義されます。child.a
のセッター メソッドが呼び出されると、 anがAttributeError
発生します。
2 番目の例でproperty()
は、デコレータではなく関数を使用することで、すべてが期待どおりに機能します。
なぜ動作が異なるのか、誰かが光を当てることができますか? また、はい、__init__
Child の定義が必要ないこともわかっています。
例 1 - 使用@property
class Parent(object):
def __init__(self):
self._a = 'a'
@property
def a(self):
return self._a
@a.setter
def a(self, val):
self._a = val
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
@property
def a(self):
return super(Child, self).a
@a.setter
def a(self, val):
val += 'Child'
super(Child, self).a = val
p = Parent()
c = Child()
print p.a, c.a
p.a = 'b'
c.a = 'b'
print p.a, c.a
例 1 return - 属性エラーを発生させます
a a
Traceback (most recent call last):
File "testsuper.py", line 26, in <module>
c.a = 'b'
File "testsuper.py", line 20, in a
super(Child, self).a = val
AttributeError: 'super' object has no attribute 'a'
例 2 -Using property()
class Parent(object):
def __init__(self):
self._a = 'a'
def _get_a(self):
return self._a
def _set_a(self, val):
self._a = val
a = property(_get_a, _set_a)
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
def _get_a(self):
return super(Child, self)._get_a()
def _set_a(self, val):
val = val+'Child'
super(Child, self)._set_a(val)
a = property(_get_a, _set_a)
p = Parent()
c = Child()
print p.a, c.a
p.a = 'b'
c.a = 'b'
print p.a, c.a
例 2 return - 正しく動作する
a a
b bChild