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?
thnx jonrsharpe, after reading Your comment, some docs and articles, MyMeta class:
from abc import ABCMeta
class MyMeta(ABCMeta):
def __init__(cls, name, bases, dct):
super(MyMeta, cls).__init__(name, bases, dct)
cls.allInstances = set()
parent class
from MyMeta import MyMeta
class Basic(object):
__metaclass__ = MyMeta
def __init__(self):
self.allInstances.add(self)
def __del__(self):
self.allInstances.remove(self)
Another way
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)