[Tutor] class instance with identity crisis

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 12 19:50:15 CET 2005



On Wed, 12 Jan 2005, Barnaby Scott wrote:

> 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



Hi Scott,

The issue with that, as you know, is that it conflicts with the way local
variables work in functions.  For example:

###
>>> def strip_and_print(x):
...     x = x.strip()
...     print x
...
>>> message = "   hello   "
>>> strip_and_print(message)
hello
>>> message
'   hello   '
###

Our reassignment to 'x' in strip_and_print has no effect on "message"'s
binding to "  hello ".  That's how we're able to use local variables as
black boxes.


For the same reasons, the reassignment to 'self in:

> class Damson:
>     def __str__(self):
>         return 'damson'
>
>     def dry(self):
>         self = Prune()

is limited in scope to the dry() method.



But can you do what you're trying to do with object composition?  That is,
would something like this work for you?

###
class Damson:
    def __init__(self):
        self.state = DamsonState()
    def __str__(self):
        return str(self.state)
    def dry(self):
        self.state = PruneState()


class DamsonState:
    def __str__(self):
        return "damson"


class PruneState:
    def __str__(self):
        return 'prune'
###


This structuring allows us to switch the way that str() applies to Damson.
The OOP Design Pattern folks call this the "State" pattern:

    http://c2.com/cgi/wiki?StatePattern


If you have any questions, please feel free to ask!



More information about the Tutor mailing list