Listing all instance of a class

前端 未结 3 1687
醉话见心
醉话见心 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条回答
  •  Happy的楠姐
    2021-01-28 07:20

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

    Output:

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

提交回复
热议问题