python - 在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
?
解决方案
试试这个:
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
推荐阅读
- mysql - mysql优化或简化SQL语句
- javascript - 能够在 TextField 中输入制表符吗?
- html - 响应式 SVG,放大 x 轴的中心而不调整大小
- javascript - 如何动态更改选项卡面板索引
- html - 如何在不使用javascript的情况下在屏幕中央打开弹出窗口?
- node.js - Heroku 上的语法错误“??=”
- visual-studio - 如何在没有互联网的情况下从 ISO 文件安装 Visual Studio 2019
- javascript - 下一个 js axios http 请求到 laravel lumen 端点并在下一个 js 应用程序中显示响应数据
- asp.net - 能够在 ASP.NET Core MVC 中使用用户名或电子邮件地址登录
- excel - 计算整个工作表中的不同值