Reputation: 11
I have two classes: One and Two
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 and Two's foo()
methods are similar enough that I feel like I'm copy-pasting code.
I know I could have a separate foo2()
method in One that executes the shared code and add arguments to foo()
for the different values, but I'm wondering if there's a better way to do this.
Upvotes: 1
Views: 40
Reputation: 22294
To extend a method from a super class, you can use 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()
Notice this will not preserve the order in which the methods are called. So if that order matters you do have to rewrite the whole foo
method.
Upvotes: 4