[Tutor] Changing a class into a subclass

Ismael Garrido ismaelgf at adinet.com.uy
Fri Mar 25 03:43:54 CET 2005

Alan Gauld wrote:

>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
My current aproach is something like that. I subclassed 
Building(Building) :-)  and wrote there the "factory" which returns self 
of the created instance. But that didn't go with all my other classes 
that have, as a design rule, that they manage the loading and saving 
from/to XML. That meant that Building was different to the other 
classes, and instead of doing:
a = Ship()

I had to do:
a = Building()

When I wrote my "factory" I thought about the dictionary approach, but I 
didn't write it because I hoped I could find something like the 
__class__ thing. Which, btw, is pure magic :-)

But there's something that I couldn't understand. In the following code, 
my guess would be that "I'm back from the death" would never get 
printed... but it is... and twice! Why?

 >>> class A:
    def pong(self):
        print self.__class__
        print "Ping!"
        self.times -=1
        if self.times >= 0:
            self.__class__ = B

 >>> class B:
    def pong(self):
        print self.__class__
        print "Pong!"
        self.times -=1
        self.__class__ = A
        print "I'm back from the death"

 >>> a = A()
 >>> a.times = 3
 >>> a.pong()
I'm back from the death  ##Weird!
I'm back from the death
 >>> a.__class__
<class __main__.A at 0x00C1AF00>


More information about the Tutor mailing list