Recursive class | can you modify self directly?
Ethan Furman
ethan at stoneleaf.us
Tue Jul 9 18:19:00 EDT 2013
On 07/09/2013 03:01 PM, Russel Walker wrote:
>
> This is a simplified example of what I want to do:
>
>
> # THIS DOESN'T WORK
> from random import choice
>
> class Expr(object):
> """
> Expr(expr, op, val) -> an expression object.
> """
>
> def __init__(self, expr, op='', val=''):
> self.expr = expr # can be another instance of Expression.
> self.op = op
> self.val = val
>
> def __str__(self):
> return ("%s %s %s" % (self.expr, self.op, self.val)).strip()
>
> def expand(self):
> self = Expr(self, choice('+-*/'), choice('12345'))
`self` is just a name. In `expand()` you are rebinding the name `self` away from the object and to a new Expr instance.
If you want to change `self` the original object you have to do something like:
def expand(self):
self.op = choice('+-*/')
self.val = choice('12345')
--
~Ethan~
More information about the Python-list
mailing list