列出一个类的所有实例

列出一个类的所有实例

本文介绍了列出一个类的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个Python模块,其中包含多个类,这些类继承自称为 MasterBlock 的单个类.我想在脚本中导入此模块,创建这些类的多个实例,然后获取此 MasterBlock 类的所有子代的所有现有实例的列表.我找到了 vars()['Blocks.MasterBlock'] .__ subclasses __()的一些解决方案,但由于我的实例是 MasterBlock 的子级,因此它不是工作.

I wrote a Python module, with several classes that inherit from a single class called MasterBlock.I want to import this module in a script, create several instances of these classes, and then get a list of all the existing instances of all the childrens of this MasterBlock class. I found some solutions with vars()['Blocks.MasterBlock'].__subclasses__() but as the instances I have are child of child of MasterBlock, it doesn't work.

这是一些示例代码:

模块:

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

推荐答案

如果将如下所示的 __ new __()方法添加到基类中,该方法将跟踪在类变量中创建的所有实例,您可以使该过程或多或少地自动化,而不必记住在每个子类的 __ init __()中调用某些东西.

If you add a __new__() method as shown below to your base class which keeps track of all instances created in a class variable, you could make the process more-or-less automatic and not have to remember to call something in the __init__() of each subclass.

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

输出:

in main of RandomA
in main of AnotherRandom
in main of AnotherRandom

这篇关于列出一个类的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:21