首页 > 解决方案 > 具有相似主体的覆盖方法

问题描述

我有两个班:一和二

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

标签: pythoninheritanceoverriding

解决方案


要从超类扩展方法,您可以使用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方法。


推荐阅读