【发布时间】:2015-05-18 08:26:06
【问题描述】:
我编写了一个 Python 模块,其中有几个类继承自一个名为 MasterBlock 的类。
我想在脚本中导入这个模块,创建这些类的几个实例,然后获取这个MasterBlock 类的所有子类的所有现有实例的列表。我找到了vars()['Blocks.MasterBlock'].__subclasses__() 的一些解决方案,但由于我拥有的实例是MasterBlock 的孩子的孩子,所以它不起作用。
下面是一些示例代码:
模块:
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
脚本:
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()
【问题讨论】:
-
@Torxed 这将如何工作?该问题要求提供 instances 的列表,而不是 attributes。
-
像这样使用全局状态通常是个坏主意。在创建
a、b和c时,最好只跟踪[a, b, c]列表。 -
@user2357112 你想如何跟踪这个?我会说问题所要求的自动跟踪是稳健的。
-
@EOL:
list_of_instances = [a, b, c]?
标签: python class python-2.7