[Tutor] class instance with identity crisis
Jeff Shannon
jeff at ccvcorp.com
Wed Jan 12 19:40:07 CET 2005
Barnaby Scott wrote:
> 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
>
> [...]
>
> but something in me suggests it should produce
>
> prune
>
> After all, 'self' refers to the instance 'weapon'.
Ah, but 'self' is a method-local name. You're re-binding that name,
not affecting the object (previously) pointed to by the name. And of
course, when the method returns, those local bindings go away.
> 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.
As others have mentioned, you can change the type of the object by
assigning to self.__class__, but this can get a bit hairy. Your
class/instance knows nothing about what names it may be bound to, so
it can't rebind those names to a different object (i.e. class Damson,
and any instances you create, know nothing of the name 'weapon').
I tend to favor the explicit approach of having weapon.dry() *return*
a different object, and then using 'weapon = weapon.dry()'. But if
you really need to have objects that change their type as a
side-effect of a method call, you can use a proxy or adapter -- in
essence, you have a class that can *contain* either a Damson or a
Prune, and which forwards method calls / attribute accesses to its
contained object.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list