get all subclasses of a class

Jason Orendorff jason at jorendorff.com
Sat Jan 19 22:50:50 EST 2002


phil hunt wrote:
> However, there are two problems with this code: 
> 
> (1) I don't know how to get a list of all the subclasses of Foo. Is this
> possible in Python?

Yes - in Python 2.2, and only if you subclass 'object'.

class X(object): pass
class Y(X): pass
class Z(X): pass
class W(Y): pass

>>> print X.__subclasses__()
[<class '__main__.Y'>, <class '__main__.Z'>]

Note that only *immediate* subclasses are returned:  children but not
grandchildren; although getting the grandchildren is an easy exercise.

> (2) in my example code, useThisClass() is a class method, which Python 
> doesn't implement.

Python 2.2 does.
http://www.python.org/2.2/descrintro.html#staticmethods

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list