Max Noel wrote:

On Mar 24, 2005, at 18:07, Ismael Garrido wrote:

Hello.

I have a program that saves/loads to/from XML. I have a main class Building, and a subclass House(Building). When I save the code I instruct each object to save itself to XML (using ElementTree), so House adds itself to the XML tree.
My problem is when I load the XML. Before having subclasses what I did was to send the XML object (again in ElementTree) to the object and 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.

Amazingly enough, you actually can do this just by rebinding self.__class__! This thread has an example: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/15afbbcd502b5450/fa111e6ea9ee4cc4

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.

This is a better approach than changing __class__ after the fact.

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to