Listing all instance of a class

前端 未结 3 1657
醉话见心
醉话见心 2021-01-28 06:42

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 instance

3条回答
  •  故里飘歌
    2021-01-28 07:34

    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)

    output:

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

提交回复
热议问题