Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if self is instance of subclass in python

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()
like image 634
lukehawk Avatar asked May 30 '26 02:05

lukehawk


1 Answers

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.

like image 180
Aran-Fey Avatar answered Jun 01 '26 15:06

Aran-Fey