【问题标题】:Calling object method inheriting from two classes调用从两个类继承的对象方法
【发布时间】:2017-10-26 14:05:16
【问题描述】:

我有三个班级ABC

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


【解决方案1】:

我无法重现您的问题。这是您定义的设置,B 继承自 A 但重载了它的方法; C 继承自 B 但又重载了它的方法。

创建C 的实例并调用hello() 使用来自C 的正确重载方法。

class A:
    def hello(self):
        print('class A method')

class B(A):
    def hello(self):
        print('class B method')

class C(B):
    def hello(self):
        print('class C method')

c = C()
c.hello()
# prints
class C method

【讨论】:

    【解决方案2】:

    我对所有课程感到困惑。我有两个看起来非常相似的对象...一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2012-08-15
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      相关资源
      最近更新 更多