[Tutor] class instance with identity crisis
Kent Johnson
kent37 at tds.net
Wed Jan 12 12:10:22 CET 2005
A couple of ideas:
You could have dry() return the new weapon:
def dry(self):
return Prune()
then the client code would be
weapon = weapon.dry()
You could have the weapon encapsulate another object and delegate to it.
Finally, you actually can change the class of an object just by assigning to self.__class__:
>>> class A:
... def show(self):
... print "I'm an A"
...
>>> class B:
... def show(self):
... print "I'm a B"
...
>>> a=A()
>>> a.__class__
<class __main__.A at 0x008CE750>
>>> a.show()
I'm an A
>>> a.__class__ = B
>>> type(a)
<type 'instance'>
>>> a.show()
I'm a B
So if you change
self = Prune()
to
self.__class__ = Prune
I think you will get the behaviour you are looking for.
I would look for another way to solve your problem, though - I agree with Pierre that this is likely
to be confusing.
Kent
Barnaby Scott wrote:
> 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!
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list