Now I know people think that Perl is unmaintainable because of its
somewhat manky syntax, but I'm starting to think that Python can be
just as evil for its interesting little ways you can totally warp
peoples mind with it in ways that probably even outdo C++ in terms of
obfuscating program flow.

Observer this little gem:

class Transformable(object):
    def transformed(self):
        pass

    def transform(self, cls):
        if not issubclass(cls, self.__class__):
            raise Exception, "Can only transform into subclassess"
        self.__class__ = cls
        self.transformed()

This nice little mixin makes it a snap to change the class of an instance
to a subclass on the fly. 

So, in action:

class Animal(Transformable):
    def make_sound(self):
        """Grrr is the well known generic animal sound!"
        print "Grrr"

class Cat(Animal):
    def make_sound(self):
        """Cats go meow!"
        print "Meow"

>>> fluffy = Animal()
>>> fluffy.make_sound()
Grrr
>>> fluffy.transform(Cat)
>>> fluffy.make_sound()
Meow

Ok cool neat little trick. But the importantly useful thing here is
(or at least useful to me in what I'm doing right now), is that
remembering Python's data model, any other references to 'fluffy' will
also be changed. So if it was stuck in a list somewhere, or reference
by another object, it would be changed there too. Pretty neat hey!

Cheers,

Benno
_______________________________________________
coders mailing list
[EMAIL PROTECTED]
http://lists.slug.org.au/listinfo/coders

Reply via email to