Python 用常规属性重写描述符
是否可以通过派生类中的常规属性重写基类中的属性,如下所示:Python 用常规属性重写描述符,python,python-2.7,Python,Python 2.7,是否可以通过派生类中的常规属性重写基类中的属性,如下所示: 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
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.
我问这个问题的原因是因为我有一个复杂的基类,其中一个描述符属性通常执行复杂的计算。但是,在其中一个派生类中,返回的值很小,必须使用另一个描述符而不仅仅是常规存储属性进行重写似乎是一种浪费。您只需在
B
中重新声明x
:
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