get all subclasses of a class

phil hunt philh at comuno.freeserve.co.uk
Sat Jan 19 15:30:17 EST 2002


I am writing a Python module, and while i know howe I can get it to work, my
solution seems (at least to me) inelegant. Is there a better way of doing
things that I'm not aware of, I am i doing it right?

My module contains a function, which returns an instance of a class,
with the exact class dependent on the parameters which the function
is invoked with. What I want is something like this:


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

class Bar2(Foo):
   #...implements useThisClass()...

class Bar3(Bar2):
   #...implements useThisClass()...

def makeAFoo(type, creationParam):
   """ make some subclass of Foo, with the class depending on (type) """
   for sc in subclasses of Foo:
      if sc.useThisClass(type):
         # got a match, so create an instance of (sc)
         return sc(creationParam)
   # didn't find anything to create, so...
   return None 


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? I know I could just make a list:

   subclassesOfFoo = (Bar, Bar2, Bar3)

but that seems a bit inelegant.

(2) in my example code, useThisClass() is a class method, which Python 
doesn't implement. I could of course fiddle it by having a constructor
that takes no arguemnts, and then construct an instance of each class
in turn and send the useThisClass() method to the temporary instance
I've just created, i.e.:

   for sc in subclasses of Foo:
      if sc().useThisClass(type):
         # got a match, so create an instance of (sc)
         return sc(creationParam)                                                           

but that too is a bit inelegant IMO.

-- 
===== Philip Hunt ===== philh at comuno.freeserve.co.uk =====
One OS to rule them all, one OS to find them,
One OS to bring them all and in the darkness bind them,
In the Land of Redmond, where the Shadows lie.





More information about the Python-list mailing list