简体   繁体   English

列出一个类的所有实例

[英]Listing all instance of a class

I wrote a Python module, with several classes that inherit from a single class called MasterBlock .我编写了一个 Python 模块,其中有几个类继承自一个名为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.我想在脚本中导入这个模块,创建这些类的几个实例,然后获取这个MasterBlock类的所有子类的所有现有实例的列表。 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.我用vars()['Blocks.MasterBlock'].__subclasses__()找到了一些解决方案,但由于我拥有的实例是MasterBlock孩子的孩子,它不起作用。

Here is some example code:下面是一些示例代码:

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]

Th ultimate goal is to be able to do:最终目标是能够做到:

for instance in list_of_instances:
    instance.main()

What about adding a class variable, that contains all the instances of MasterBlock ?添加一个包含MasterBlock所有实例的类变量怎么样? You can record them with:您可以通过以下方式记录它们:

Class MasterBlock(object):

    all_instances = []  # All instances of MasterBlock

    def __init__(self,…):
        …
        self.all_instances.append(self)  # Not added if an exception is raised before

You get all the instances of MasterBlock with MasterBlock.all_instances (or instance.all_instances ).您可以使用MasterBlock.all_instances (或instance.all_instances )获得MasterBlock所有instance.all_instances

This works if all base classes call the __init__ of the master class (either implicitly through inheritance or explicitly through the usual super() call).如果所有基类都调用主类的__init__ (通过继承隐式或通过通常的super()调用显式调用),则此方法有效。

Here's a way of doing that using a class variable:这是使用类变量的一种方法:

class MasterBlock(object):
    instances = []
    def __init__(self):
        self.instances.append(self)
    def main(self):
        print "I am", self

class RandomA(MasterBlock):
    def __init__(self):
        super(RandomA, self).__init__()
        # other init...

class AnotherRandom(MasterBlock):
    def __init__(self):
        super(AnotherRandom, self).__init__()
        # other init...


a = RandomA()
b = AnotherRandom()
c = AnotherRandom()
# here I need to get list_of_instances=[a,b,c]

for instance in MasterBlock.instances:
    instance.main()

(you can make it simpler if you don't need __init__ in the subclasses) (如果您在子类中不需要__init__ ,您可以使它更简单)

output:输出:

I am <__main__.RandomA object at 0x7faa46683610>
I am <__main__.AnotherRandom object at 0x7faa46683650>
I am <__main__.AnotherRandom object at 0x7faa46683690>

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.如果您将如下所示的__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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM