0

我正在尝试创建具有保存所有已创建实例集的机制的基本抽象类。

class Basic(object):
    __metaclass__ = ABCMeta
    allInstances = set()

    def __init__(self, name):
        self.allInstances.add(self)

    def __del__(self):
        self.allInstances.remove(self)

问题是 setallInstances保存了所有子类的实例。我应该为每个子类单独添加这些行,还是有办法为基本类中的每个子类创建集合?

4

1 回答 1

0

thnx jonrsharpe,在阅读了您的评论、一些文档和文章、MyMeta 类之后:

from abc import ABCMeta

class MyMeta(ABCMeta):
    def __init__(cls, name, bases, dct):
        super(MyMeta, cls).__init__(name, bases, dct)
        cls.allInstances = set()

父类

from MyMeta import MyMeta

class Basic(object):
    __metaclass__ = MyMeta

    def __init__(self):
        self.allInstances.add(self)

    def __del__(self):
        self.allInstances.remove(self)

其他方式

from abc import ABCMeta, abstractmethod

class Basic(object):
    __metaclass__ = ABCMeta

    allInstances = None 

    def __init__(self):
        if self.__class__.allInstances is None:
            self.__class__.allInstances = set()
        self.__class__.allInstances.add(self)

    def __del__(self):
        self.__class__.allInstances.remove(self)
于 2015-09-29T13:02:53.750 回答