Listing all instance of a class

前端 未结 3 1652
醉话见心
醉话见心 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条回答
  •  -上瘾入骨i
    2021-01-28 07:18

    What about adding a class variable, that contains all the instances of 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).

    This works if all base classes call the __init__ of the master class (either implicitly through inheritance or explicitly through the usual super() call).

提交回复
热议问题