Trying to generate a list of the subclasses of C

Diez B. Roggisch deets at nospam.web.de
Mon Jan 16 08:30:34 EST 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):
        subclassesofc.append(name)
        return type.__new__(cls, name, bases, dict)

class C(object):
    __metaclass__ = SubclassCollector



class A(C):
    pass

print subclassesofc



Regards,

Diez



More information about the Python-list mailing list