Trying to generate a list of the subclasses of C

Diez B. Roggisch deets at
Mon Jan 16 14:30:34 CET 2006

> The end result I'm after is an automatically generated dictionary
> containing instaces of the subclasses keyed by the subclass names:
> {'D':D(), 'E':E(), . . . }
> I can see the information I need in the module's __dict__ and by using
> the dir() method, but I'm not having much success extracting it.

Use a metaclass:

subclassesofc = []

class SubclassCollector(type):

    def __new__(cls, name, bases, dict):
        return type.__new__(cls, name, bases, dict)

class C(object):
    __metaclass__ = SubclassCollector

class A(C):

print subclassesofc



More information about the Python-list mailing list