On Tue, Jul 9, 2013 at 4:01 PM, Russel Walker <russ.po...@gmail.com> wrote: > Sorry for the vague title. Probably best to just show you the code that > explains it better. > > 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 local binding of the object to the name self. You can rebind the name like this as with any other local variable, but that's all it does. It doesn't modify the object in any way, and no other bindings of the same object are affected. If you actually want to modify the current object, you would need to do something like: def expand(self): import copy self.expr = Expr(self.expr, self.op, self.val) self.op = choice('+-*/') self.val = choice('12345') -- http://mail.python.org/mailman/listinfo/python-list