I have a class called A, with two subclasses B and C. Does the following make sense? Or is there a better way to it?
class A():
...
def do_stuff(self):
self.do_this()
self.do_that()
if isInstance(self, B):
self.do_the_b_stuff()
elif isInstance(self, C):
self.do_the_c_stuff()
There's a better way to do it: Override do_stuff in the child classes.
class A:
def do_stuff(self):
self.do_this()
self.do_that()
class B(A):
def do_stuff(self):
super().do_stuff() # call the parent implementation
self.do_the_b_stuff()
class C(A):
def do_stuff(self):
super().do_stuff() # call the parent implementation
self.do_the_c_stuff()
The advantage of this solution is that the base class doesn't have to know about its child classes - B and C aren't referenced anywhere in A's body. This makes it easier to add additional subclasses, should that ever be necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With