在知乎上看到以下代码不能工作
class Base(object):
def __init__(self):
self._value = 10
def __repr__(self):
return 'Value(%s)' % self._value
@property
def value(self):
return self._value
@value.setter
def value(self, v):
self._value = v
class Derived(Base):
@property
def value(self):
return super(Derived, self).value * 2
@value.setter
def value(self, v):
super(Derived, self).value = v / 2
Derived的super(Derived, self).value = v / 2
会抛异常
AttributeError: 'super' object has no attribute 'value'
查了CPython的代码发现原来super这个代理类没有实现赋值操作符,只是实现了取值tp_getattro
PyTypeObject PySuper_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"super", /* tp_name */
....
super_getattro, /* tp_getattro */
0, /* tp_setattro */
....
}