3

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()

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the edit. I appreciate knowing why this is better, and that makes great sense. Thanks for the answer too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.