Keeping track of subclasses and instances?
akraemer at sbcglobal.net
Thu Oct 11 07:49:23 CEST 2007
On Oct 10, 6:19 pm, Karlo Lozovina <_kar... at mosor.net> wrote:
> Larry Bates wrote:
> > I'm not completely sure I understand the question but here goes.
> > Instances of
> > classes are classes can be stored in lists or dictionaries. In lists you
> > reference them via their index (or iterate over them) and in dictionaries
> > you can give them a name that is used as a key.
> I wish if it were that simple :).
> Here is a longer description - I have a function that given input creates a
> custom class and returns it back. The user is free to subclass that (even
> more, he should do that), and of course he will make instances of those
> subclasses. Now, my question is how to keep track of subclasses and their
> instances, without the need for user interaction (appending them to a list,
> or adding to dictionary)?
> Karlo Lozovina - Mosorclass Meta(type):
What about the following solution?
class_ = super(Meta,mcl).__new__(mcl,*args,**kw)
class_._instances = 
_classes = 
__metaclass__ = Meta
instance = super(Class,cls).__new__(cls,*args,**kw)
>>> A = factory()
>>> class B(A): pass
>>> a = A()
>>> b = B()
[<class 'meta.Class'>, <class '__main__.B'>]
[<meta.Class object at 0xb7dbb08c>]
[<__main__.B object at 0xb7dbb0ec>]
So, you see that you can access all classes, their subclasses, and
instances from Meta.
Of course in a more elaborate version _classes and _instances should
store weak references, so that classes and instances can actually be
deleted. I also haven't explored under which circumstances this can
I can imagine different use cases for this, (though they certainly are
non-standard :-)). I once contemplated the (toy-) implementation of a
frame-based knowledge representation system using Python's object
model, where one definitely needs classes to keep track of their
More information about the Python-list