Friday, July 31, 2009

Smalltalk's become() in python

Posting this here because blogger's sucky comment system won't let me post formatted code in a comment on this post. This is an implementation of Smalltalk's become() in python. It will not work on strings, int etc. but otherwise is identical

#! /usr/bin/python def become(a, b): swap(a, b, "__class__") swap(a, b, "__dict__") def swap(a, b, attr): tmp = getattr(a, attr) setattr(a, attr, getattr(b, attr)) setattr(b, attr, tmp) class Animal(object): def __init__(self, name): self.name = name class Dog(Animal): def Cry(self): print "%s says woof" % self.name class Sheep(Animal): def Cry(self): print "%s says baa" % self.name a = Dog("rover") b = Sheep("shaun") c = a a.Cry() c.Cry() become(a, b) a.Cry() c.Cry()
This prints
rover says woof rover says woof shaun says baa shaun says baa
Note how both a and c are now sheep. To do the same thing in perl you monkey around with bless and resetting all the hash entries, it's a bit uglier.

No comments: