首页 > 解决方案 > 在python中调用Parent类的所有子类

问题描述

假设我们有一个父类,如下所示

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

我创建了几个定义sth()方法的子类,如下所示

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

我将如何调用sth()所有子类的方法?

目前,我只是将这些类添加到一个列表中,并基于一个 for 循环,sth()对所有这些类调用该方法。因为该方法在每个类中都实现了,所以他们都理解它并知道他们是否应该处理任务(不确定这是否是最好的方法)

有没有办法基本上调用sth()从 class 继承的所有类的方法P

标签: pythonpython-3.xinheritance

解决方案


试试这个:

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

输出是:

Base Implementation
Implementation a
Implementation b
Implementation c

推荐阅读