我编写了一个 Python 模块,其中有几个类继承自一个名为MasterBlock
。
我想在脚本中导入此模块,创建这些类的多个实例,然后获取该类的所有子级的所有现有实例的列表MasterBlock
班级。我找到了一些解决方案vars()['Blocks.MasterBlock'].__subclasses__()
但由于我的例子是孩子的孩子MasterBlock
,它不起作用。
这是一些示例代码:
Module:
Class MasterBlock:
def main(self):
pass
Class RandomA(MasterBlock):
def __init__(self):
pass
# inherit the main function
Class AnotherRandom(MasterBlock):
def __init__(self):
pass
# inherit the main function
Script:
import module
a=module.RandomA()
b=module.AnotherRandom()
c=module.AnotherRandom()
# here I need to get list_of_instances=[a,b,c]
最终目标是能够做到:
for instance in list_of_instances:
instance.main()
如果您添加一个__new__()
如下所示的方法添加到您的基类中,该方法跟踪在类变量中创建的所有实例,您可以使该过程或多或少自动化,而不必记住调用__init__()
每个子类。
class MasterBlock(object):
instances = []
def __new__(cls, *args, **kwargs):
instance = super(MasterBlock, cls).__new__(cls, *args, **kwargs)
instance.instances.append(instance)
return instance
def main(self):
print('in main of', self.__class__.__name__) # for testing purposes
class RandomA(MasterBlock):
def __init__(self):
pass
# inherit the main function
class AnotherRandom(RandomA): # works for sub-subclasses, too
def __init__(self):
pass
# inherit the main function
a=RandomA()
b=AnotherRandom()
c=AnotherRandom()
for instance in MasterBlock.instances:
instance.main()
Output:
in main of RandomA
in main of AnotherRandom
in main of AnotherRandom
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)