Manuel
Manuel

Reputation: 802

Calling all childs of a Parent class in python

Lets say we have a parent class like the following

class P():
    @staticmethod
    def sth():
        pass

And I create several child classes that define the sth() method, something like the following

class P_a(P):
    @staticmethod
    def sth():
        #Implementation a

class P_b(P):
    @staticmethod
    def sth():
        #Implementation b

class P_c(P):
    @staticmethod
    def sth():
        #Implementation c

How would I call the sth() method of all the child classes?

At the moment, I'm just adding the classes to a list and, based on a for loop, calling the sth() method on all of them. Because that method is implemented in every class, all of them understand it and know if they should take care of the task or not (Not sure if this is the best way of doing this tho)

Is it there a way of basically calling the sth() method of all the classes that inherit from class P?

Upvotes: 0

Views: 63

Answers (1)

ErdoganOnal
ErdoganOnal

Reputation: 880

Try this:

class P:
    subclasses = []

    def __init_subclass__(cls, *args, **kwargs) -> None:
        P.subclasses.append(cls)

    @staticmethod
    def sth():
        print("Base Implementation")

    @classmethod
    def call_all_sth(cls):
        cls.sth()
        for klass in cls.subclasses:
            klass.sth()

class P_a(P):
    @staticmethod
    def sth():
        print("Implementation a")

class P_b(P):
    @staticmethod
    def sth():
        print("Implementation b")

class P_c(P):
    @staticmethod
    def sth():
        print("Implementation c")

P.call_all_sth()

Output is:

Base Implementation
Implementation a
Implementation b
Implementation c

Upvotes: 2

Related Questions