class A(object):
_all = set()
def __new__(cls):
obj = super(A,cls).__new__(cls)
cls._all.add(obj)
return obj
class B(A):
pass
class C(A):
pass
b = B()
c = C()
This will create all instances and put them in A._all. What I want is for the instances of C to be placed in C._all (and similarly for C).
I could define B and C like this:
class B(A):
_all = set()
class C(A):
_all = set()
Which would work. However, this feels like repeating code, and if I forget to add _all when I subclass A next, or misspell _alll I’m likely to get hard to debug errors.
How would I go about doing this well?
Here’s a metaclass for it:
In Python 3, the definition for
Amust be: