1
我在添加属性时遇到尝试继承python类的问题。为了说明这一点,确定以下类别:在添加属性时继承python类
class A:
def __init__(self, prop, x1, x2):
self.prop = prop
self.x = x1 + x2
class B(A):
def __init__(self, prop, x1, x2):
super().__init__(prop, x1, x2)
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self._prop = value + 10
现在类B
要调用类A
的__init__
方法,它会调用B.prop
的制定者。但我不想这样做,而是直接设置_prop
。有没有一个很好的方法来实现这一目标?
以下是我通过尝试检测我们是否在__init__
而提出的解决方案,但我希望听到一些替代方案。
class B(A):
def __init__(self, prop, x1, x2):
super().__init__(prop, x1, x2)
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
if hasattr(self, '_prop'):
self._prop = value + 10
else:
self._prop = value
我很难想象这个用例...?你介意解释你想达到的目标吗?这可能会导致更广泛地投入到您之后的设计模式中。 – 2014-09-02 23:51:27
我明白了你的观点,这有点难,但我会尝试给出更具体的用例。 – simonzack 2014-09-03 00:08:04