[Tutor] Confused about functions

Kalle Svensson kalle@gnupung.net
Thu, 1 Nov 2001 13:02:48 +0100


[Kit O'Connell]
> def changer (x,y):
> 	x = 2
> 	y[0] = 'spam'
> 
> X = 1
> L = [1, 2]
> changer (X, L)

> I am confused. Why does L change, but X doesn't? I hope someone can
> explain this for me a bit.

This is a nice example of how things that look very similar can be very
different...  The key thing to notice here is that
y[0] = 'spam'
isn't an assignment in the same way that
x = 2
is.
The ordinary assignment operator works by binding a name, 'x' in this
case, to an object, here the integer object '2'.  These names are available in
different namespaces and scopes which I suppose Learning Python discusses.

y[0] = 2 isn't really an assignment, it's more like a method call.  This can
be illustrated if we substitute instances of a pointless little class for the
variables in the example:

### begin ###
class A:
    stuff = "Not set!"
    def __setitem__(self, key, val):
        self.stuff = (key, val)
    def __str__(self):
        return "Instance of class A: %s" % self.stuff

a, b = A(), A()
print a, b
a = 2
b[0] = 2
print a, b
### end ###

When run, this will result in:

Instance of class A: 'Not set!' Instance of class A: Not set!
2 Instance of class A: (0, 2)

'a' has been rebound to an integer, 'b' is still the same object, but the
special method __setitem__ has been called.
Nice, eh?

Peace,
  Kalle
-- 
[ Thought control, brought to you by the WIPO! ]
[ http://anti-dmca.org/ http://eurorights.org/ ]