[Tutor] Changing a class into a subclass

Alan Gauld alan.gauld at freenet.co.uk
Thu Mar 24 22:41:59 CET 2005


> > let itself load. Now, with subclasses, if I send the House XML to
> > Building I get a Building instance, when I need a House instance.
>
> You can't make an object transform into an object of a different
> class. You need to identify what class the object will be an
instance
> of before loading it. Which, if you're using XML tags like <Building
> type="House"> or <House>, shouldn't be very difficult to do.

Absolutely, looks like you answered your own question... :-)

But if you want an OOP approach thre are some things to try.
First you can create a BuildingFactory class that has a
single instance (or indeed no instances because you could
use a static method... or get really fancy and create a
meta-class!). The factory class then takes the XML string
fragment and figures out which subclass of Building to
create and returns the required object. You can avoid
having to recode the factory class each time by using a
dictionary object and each subclass definition adds an entry
to the Factory class dictionary - possibly by calling a
class method of Building in the __init__() code


class Shack(Building):
   def __init__(self,p1,p2...):
      Building.__init__(self,...)
      Building.register(self,'Shack', Shack)
      ...rest of init...

Now the factory code can go
     name = self.getClassName(xmlString)
     obj = self.classList[name]()

and instantiate a Shack object.

But unless you expect to create an awful lot of subclasses,
or just want to be purist in approach its probably overkill!

Alan G.



More information about the Tutor mailing list