python - 具有相似主体的覆盖方法

标签 python inheritance overriding

我有两个类(class):一类和二类

class One:
    # self.a, self.b, self.c
    # ...
    def foo(self):
        self.a.foo()
        self.b.bar()
        self.c.hmm(1,2,3)

class Two(One):
    # super(Two, self).__init__()
    # self.d
    # ...
    def foo(self):
        self.a.foo()
        self.b.bar()
        self.d.wow()
        self.c.hmm(4,5,6)

One 和 Two 的 foo() 方法非常相似,以至于我觉得我在复制粘贴代码。 我知道我可以在 One 中有一个单独的 foo2() 方法来执行共享代码并为不同的值向 foo() 添加参数,但我想知道是否有更好的方法来做到这一点。

最佳答案

要从父类(super class)扩展方法,可以使用 super

class One:
    ...

    def foo(self):
        self.a.foo()
        self.b.bar()
        self.c.hmm(1,2,3)

class Two(One):
    ...

    def foo(self):
        super().foo()
        self.d.wow()

请注意,这不会保留调用方法的顺序。因此,如果该顺序很重要,您就必须重写整个 foo 方法。

关于python - 具有相似主体的覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56940499/

相关文章:

python - 无法使用 Selenium for Python 打开 Chrome WebDriver

python - Python中高效的任意大小的整数打包

python - Python 中具有接口(interface)和继承的多级抽象

c++ - 为什么派生类不能访问基类静态方法?

ruby - 实例变量继承

c# - 隐藏基类中存在的方法

java - 覆盖 Java 中的 protected 方法

python - Pytest 是一种类型的实例

Python with 语句——是否还需要旧式文件处理?

java - 重写 equals 方法问题