Simple Class/Variable passing question

Matt Nordhoff mnordhoff at mattnordhoff.com
Thu Jun 19 18:37:09 EDT 2008


monkeyboy wrote:
> Hello,
> 
> I'm new to python, and PythonCard. In the code below, I'm trying to
> create a member variable (self.currValue) of the class, then just pass
> it to a simple function (MainOutputRoutine) to increment it. I thought
> Python "passed by reference" all variables, but the member variable
> doesn't seem to be incremented. If I make the function just increment
> the member variable directly, without passing it in, it works fine?
> 
> In the code below, "self.currValue" stays at 5, and value evaluates to
> 1? Any insight would be appreciated...
> 
> 
> class TestModel(model.Background):
> 
>     def on_initialize(self,event):
>         self.currValue = 5
> 
>     def on_startBtn_mouseClick(self, event):
>         self.MainOutputRoutine(self.currValue)
>         self.OutputRoutine(self.currValue)
> 
>     def OutputRoutine(self,value):
>         self.components.txtBox1.text = str(value)
> 
>     def MainOutputRoutine(self,value):
>         value = value + 1

That's not how Python works. When you call
"self.MainOutputRoutine(self.currValue)", in that method's scope, the
local name "value" points to the same object as self.currValue does.
When you do "value = value + 1", the local name "value" now points to a
different object. That has no bearing on self.currValue.

Err, I can't find a guide here. Um, read the language spec? I dunno.

However:

>>> my_list = [1]
>>> def function(l):
...     l.append(2)
>>> function(my_list)
>>> my_list
[1, 2]

That's because function() is *mutating* the list; it's not changing what
the "l" name points to. It's calling the "append" method of the list
object, which changes said list object. If it were doing, say, "l = 42",
that would only rebind the function's local name "l":

>>> my_list = [1]
>>> def function(l):
...     l = 42
>>> function(my_list)
>>> my_list
[1]

Note that strings and integers are immutable, so whenever you think
you're mutating them (e.g. "s.replace('a', 'b')" or "i += 1"), you're
actually getting a whole new, different object, with all that that implies.
-- 



More information about the Python-list mailing list