[Tutor] class instance with identity crisis

Barnaby Scott bds at waywood.co.uk
Wed Jan 12 10:35:02 CET 2005


This is probably a very easy question, and one that I was shocked to find I
was stuck on, having thought I understood classes!

I was wondering how you can get an instance of a class to change itself into
something else (given certain circumstances), but doing so from within a
method. So:

class Damson:
    def __str__(self):
        return 'damson'

    def dry(self):
        self = Prune()

class Prune:
    def __str__(self):
        return 'prune'

weapon = Damson()
weapon.dry()
print weapon

All the old hands will of course know this will produce the output

damson

but something in me suggests it should produce

prune

After all, 'self' refers to the instance 'weapon'.

Obviously one could reassign weapon to a Prune outside the class definition,
but I was hoping to write something in which, given certain circustances
arising, the instance would change itself into something else.

Time to go back to school!



More information about the Tutor mailing list