【问题标题】:In Python, is there any way to call a child class's method override from its parent class?在 Python 中,有没有办法从其父类调用子类的方法覆盖?
【发布时间】:2019-10-30 09:49:54
【问题描述】:

我正在尝试重新自学 Python,并找出具体的细节、技巧和窍门,以及围绕抽象类和多态的常见约定。现在,我有一个如下所示的类层次结构:

from abc import ABC, abstractmethod


class A(ABC):

    @abstractmethod
    def x(self):
        pass

    def do_x_ten_times(self):
        for i in range(10):
            x()


class B(A):

    def x(self):
        print("Hello World")


class C(A):

    def x(self):
        print("Hello StackOverflow")



b = B()
b.x()

c = C()
c.x()

b.do_x_ten_times()

我的想法是 do_x_ten_times() 在子类 BC 中的代码完全相同。因此,如果我可以将 do_x_ten_times() 的代码放在 A 中,并且无论子类的实现如何都可以调用 A x() 是。不幸的是,我得到“NameError: name 'x' is not defined。”

我明白为什么做这样的事情可能不典型,我的直觉说这可能违反了某些多态性规则。如果我真的需要,我可以将 do_x_ten_times() 复制粘贴到 BC 两个类中,并在 中使其抽象化一个。但我想知道是否有任何合理的方法可以不必重复此代码。

【问题讨论】:

    标签: python inheritance polymorphism abstract-class subclass


    【解决方案1】:

    您需要在A.do_x_ten_times()中拨打self.x()

    from abc import ABC, abstractmethod
    
    
    class A(ABC):
    
        @abstractmethod
        def x(self):
            raise NotImplementedError
    
        def do_x_ten_times(self):
            for i in range(10):
                self.x()        # <-- self will refer to the calling instance
                                #     implementation of x(self)
    
    
    class B(A):
    
        def x(self):
            print("Hello World")
    
    
    class C(A):
    
        def x(self):
            print("Hello StackOverflow")
    
    
    
    b = B()
    b.x()
    
    c = C()
    c.x()
    
    b.do_x_ten_times()
    

    【讨论】:

    • 谢谢!我很笨!编辑:我发布的代码只是我快速制作了一个更大脚本的简单版本,你瞧,我犯了同样的错误
    猜你喜欢
    • 2017-11-11
    • 2010-09-06
    • 2020-08-29
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2018-07-08
    相关资源
    最近更新 更多