是否可以通过派生类中的常规属性覆盖基类中的属性,如下所示:
class A(object):
@property
def x(self):
return self._x
@x.setter
def x(self, y):
self._x = y
class B(A):
def __init__(self, y):
self.x = y #the descriptor methods are not called and
#"x" is a regular attribute in the object dict.
我要问的原因是因为我有一个复杂的基类,其中一个描述符属性通常会执行复杂的计算。但是,在其中一个派生类中,返回的值是微不足道的,似乎不得不用另一个描述符而不是常规存储属性来覆盖是一种浪费。
答案 0 :(得分:2)
您只需在x
中重新声明B
:
class A(object):
@property
def x(self):
print("calculating x...")
return self._x
@x.setter
def x(self, y):
print('setting x...')
self._x = 10*y
class B(A):
x = None
def __init__(self, y):
self.x = y #the descriptor methods are not called and
#"x" is a regular attribute in the object dict.
b = B(3)
print(b.x)
# 3