Charles Krug a écrit : > List: > > I have this: > > # classC.py > > class C(object): pass > > class D(C): pass > > class E(C): pass > > def CSubclasses(): > for name in dir(): pass > > I'm trying to create a list of all of C's subclasses: > > import classC > > print C > aList = [] > for name in dir(classC): > print name, > try: > if issubclass(classC.__dict__[name], C): > print classC.__dict__[name] > else: > print > except TypeError: > print >
Where is C defined ? >>> import classC does not define the name C in the current scope ... thus, you should write : for name in dir(classC): print name, try: if issubclass(classC.__dict__[name], classC.C): print classC.__dict__[name] else: print except TypeError: print and it gives : C <class 'test_subclass.C'> CSubclasses D <class 'test_subclass.D'> E <class 'test_subclass.E'> __builtins__ __doc__ __file__ __name__ ... which is exactly what you want ! Pierre > Which gives me this: > > <class '__main__.C'> > C > CSubclasses > D > E > __builtins__ > __doc__ > __file__ > __name__ > > However when I do this from the command line: > > >>>>issubclass(D,C) > > True > > but > > >>>>issubclass(classC.__dict__['D'], C) > > False > > So my approach is flawed. > > 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. > > > -- http://mail.python.org/mailman/listinfo/python-list