0

I'm trying to create basic abstract class with mechanism for saving of set of all created instances.

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

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

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

The problem is that set allInstances saves instances of all child classes. Should I add this lines for every child class separately or there is way to create sets for every child class in basic class?

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 に答える