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?

Azazell00
  • 93
  • 8
  • I like Marty Alchin's [plugin pattern](http://martyalchin.com/2008/jan/10/simple-plugin-framework/) for things like this. – Daniel Roseman Sep 28 '15 at 16:07
  • 1
    If you want to have a separate class attribute for each sub-class, that should be part of the metaclass (which can inherit from `ABCMeta`). – jonrsharpe Sep 28 '15 at 16:08
  • Interesting thing, when I add integer class variable into my class `Basic`(the same way as `allInstances` - it creates separately for every child class. How it can be explained? – Azazell00 Sep 29 '15 at 14:36
  • Note that `__del__` isn't guaranteed to always be called. This is especially true in python<3.4. Basically any cycle of objects with that method will be deallocated without calling it. – Bakuriu Sep 30 '15 at 12:01

1 Answers1

0

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)
Azazell00
  • 93
  • 8