Function args

Peter Otten __peter__ at web.de
Fri Apr 9 04:06:25 EDT 2004


Jean-Michel Caricand wrote:

> Imaginons que je veuille écrire une fonction qui permute deux variables,
> j'écris :
> 
> def permuter(a,b):
>   c = b
>   b = a
>   a = c
> 
> Si tout est objet, donc passé par référence a et b devraient être
> réellement modifier ? Pourtant ce n'est pas le cas.

Assignments inside a function only affect local bindings, i. e what a and b
"point" to in the local context. Rebinding in the calling context must be
made explicit:

>>> a = 1
>>> b = 2
>>> a, b = swap(a, b)
>>> a
2
>>> b
1

Of course you wouldn't write a function for that particular example:

>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1
>>>

Does the above mean you can never change an object from inside a function?
No, only bindings cannot be changed and because integers are "immutable",
i. e. cannot be changed once they are created, what is viewed as changing
them is in fact rebinding. Now a simple example with a mutable class:

>>> class A:
...     def __init__(self, name, value):
...             self.name = name
...             self.value = value
...     def __repr__(self):
...             return "A(name=%r, value=%r)" % (self.name, self.value)
...
>>> def swapAttr(a, b):
...     a.value, b.value = b.value, a.value
...
>>> a = A("A", 1)
>>> b = A("B", 2)
>>> a, b
(A(name='A', value=1), A(name='B', value=2))
>>> swapAttr(a, b)
>>> a, b
(A(name='A', value=2), A(name='B', value=1))

While objects stay the same, you can do anything with the attributes. As
Michel Claveau already pointed out, the same is true for list and dict
items. 

Peter




More information about the Python-list mailing list