【发布时间】:2017-10-26 14:05:16
【问题描述】:
我有三个班级A、B 和C。
A 有一个方法hello(self)。 B 继承自 A 并实现了一个新方法 hello(self)。 C 继承自 B 并重新实现了方法 hello(self)。
现在,如果我创建一个实例 b = B() 并调用 b.hello() 它应该调用 B.hello(b)。
问题是当我创建一个对象c = C() 并调用c.hello() 它实际上调用B.hello(c) 而不是C.hello(c)。这是为什么呢?
我的代码如下所示:
class A:
def hello(self):
self.helloHandler()
def helloHandler(self):
print('class A method')
class B(A):
def helloHandler(self):
print('class B method')
class C(B):
def helloHandler(self):
print('class C method')
c = C()
c.hello()
这行得通,但不是我的。我的代码此时有几千行......不能真正发布它,但这就是重点。我不知道可能是什么问题。如果出于某种模糊的原因强制子类实现某些方法很重要,我会使用 abcmeta。
编辑:我弄乱了两个看起来相同的对象。一切正常!
【问题讨论】:
-
发布您的代码。
-
如果您使用的是元类,则不应重载父类中定义的具体方法,这些方法是从 ABC 中定义的抽象方法继承而来的。
-
投票结束,因为问题无法重现。
标签: python inheritance methods extends