get all subclasses of a class

Emile van Sebille emile at fenx.com
Sun Jan 20 05:09:54 CET 2002


phil hunt
> (1) I don't know how to get a list of all the subclasses of Foo. Is
this
> possible in Python? I know I could just make a list:
>
>    subclassesOfFoo = (Bar, Bar2, Bar3)
>
> but that seems a bit inelegant.
>

How about:


class Foo: #abstract superclass
    def useThisClass(self, type):
       return 0 # Foo is abstract, so we never create any instances of
it

class Bar(Foo): pass

class Bar2(Foo): pass

class Bar3(Bar2): pass

def testfooness(arg):
    try: return issubclass(arg, Foo) and arg != Foo
    except: return None

subclassesOfFoo = [ sc[0] for sc in vars().items() if
testfooness(sc[1]) ]


--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list