Recursive class | can you modify self directly?

Russel Walker russ.pobox at gmail.com
Wed Jul 10 10:58:49 CEST 2013


I didn't do a good job of explaining it cos I didn't want it to be a TLDR; but I could've added a little more. To clarify:

Expr is just a way to represent simple arithmetic expressions for a calculator. Because the expression has to be modified and built over time, and evaluated from left to right and not by operator precedence, I thought it would be simpler to do it this way.

Say the calculation in the calculator is currently at:
1 + 2 * 3

Now lets expand it out to see how it gets to this point.

dial 1: (1)             >>> x = Expr(1) # the base case
dial +: ((1) + )        >>> x = Expr(x, '+')
dial 2: ((1) + 2)       >>> x.val = 2
dial *: (((1) + 2) + )  >>> x = Expr(x, '+')
dial 3: (((1) + 2) + 3) >>> x.val = 3

I think it's called 'binary tree' but not entirely sure if that's correct.


So I think understand what you guys are saying now.

There is the name x and the class instance (the object) which exists somewhere in memory that x points to. self is just another name that points to the same object (not self in general but the argument passed to the self parameter when a method is called). However if the code inside the method reassigns self to some other object, it doesn't change the fact that x still refers to the original object. So self is just a local variable (an argument). The name self has no relevance to to the name x other than the fact that they point to the same object. So reassigning self has no effect on x. But modifying the object that self points to, does affect x because it points to the same object. Is this correct?


So when you call x.somemethod() it's not passing x as the self argument, it's actually passing the object that x points to as the self argument. And that object has know knowledge of the fact that x points to it, or does it?



More information about the Python-list mailing list