我有两个类(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/