Rya*_*yan 3 python inheritance properties
在我的代码中,类A具有属性,但是类B不继承它。是否@property支持继承?还是我的错?
class A(object):
def __init__(self):
self._x = 100
@property
def x(self):
return self._x
@x.setter
def x(self, v):
self._x = v
class B(A):
@x.setter
def x(self, v):
self._x = v
Run Code Online (Sandbox Code Playgroud)
错误消息如下:
Traceback (most recent call last):
File "test.py", line 9, in <module>
class B(A):
File "test.py", line 10, in B
@x.setter
NameError: name 'x' is not defined
Run Code Online (Sandbox Code Playgroud)
之所以这样NameError是因为x不在全球范围内。它是在A类名称空间中定义的,因此您需要使用在那里显式访问它A.x。这是一个非常常见的错误,请参见例如python子类对parent的类变量的访问。
但是,有了属性,它可能会变得稍微复杂一些。如果你添加一个新的二传中B,那么就使用没有问题A.x.setter,如图院长的回答。但是,如果您覆盖现有的setter,那么您还将更改A的行为。我怀疑这是您想要的行为。
相反,在这种情况下,您需要使用A的getter和新的setter 在子类中创建一个新的属性。我认为这是最简单的方法,只需最少的重复即可:
class B(A):
x = property(A.x.__get__) # new property with same getter
@x.setter # new setter on new property
def x(self, v):
...
Run Code Online (Sandbox Code Playgroud)
注意property不使用@语法糖,因为我没有用它来装饰新方法。如果您想A从B的设置者中访问的设置者,则可以使用super().x.__set__(whatever)。