列出类的所有实例

时间:2015-05-18 08:26:06

标签: python class python-2.7

我编写了一个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()

3 个答案:

答案 0 :(得分:2)

添加一个包含MasterBlock所有实例的类变量怎么样?您可以使用以下方式录制它们:

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

您获得MasterBlock MasterBlock.all_instances(或instance.all_instances)的所有实例。

如果所有基类都调用主类的__init__(通过继承隐式或通过通常的super()调用显式调用),则此方法有效。

答案 1 :(得分:2)

以下是使用类变量的方法:

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

(如果你在子类中不需要__init__,你可以更简单)

输出:

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

答案 2 :(得分:2)

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

输出:

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