Indexed variables

Laszlo Zsolt Nagy gandalf at designaproduct.biz
Thu Sep 22 13:09:25 EDT 2005


>a1=a2=0
>
>def f(x):
>    if x == a1:
>        a1 = a1 + 1
>    elif x == a2:
>        a2 = a2 + 1
>
>
>Now if I call f with f(a2) only a1, of course, is incremented because the
>if-clause does only check for the value of the input and the values of a1
>and a2 are identical.
>
>So how do I define the function such as to discrimate wheter I call it by 
>f(a1) or f(a2) ?
>  
>
What you are trying to do is to create a function with a side effect. 
(Side effect is when a function changes its environment. The environment 
of a function is everything that is not local to that function, plus the 
actual parameters and I/O devices.)

If you really want to change an actual parameter inside an object, then 
you should use a mutable object. In Python, there are two kinds of 
objects: mutable and immutable. Immutable objects cannot change their 
value. Integers are immutable. The object zero will always be zero. You 
can add another integer to it, but it will create another object, while 
the zero object will remain zero. There are other immutable objects. For 
example, tuples are immutable.

 >>>t = (1,2,3)

This object is an immutable tuple. You cannot change its value. Mutable 
objects can change their values. For example, lists are mutable.

 >>>L = [1,2,3]

Usually, mutable objects have methods to change their value.

 >>>L.append(4)
 >>>print L

[1,2,3,4]

So if you really want to create a function with a side effect, do 
something like this:

>>>
>>> a1 = [0]
>>> a2 = [0]
>>>
>>>
>>> def f(x):
...     if x is a1:
...         a1[0] += 1
...     elif x is a2:
...         a2[0] += 1
...
>>> a1
[0]
>>> f(a1)
>>> a1
[1]
>>> a2
[0]
>>>


But please note that having side effect is generally considered harmful.

Please read the tutorial, these things are explained quite well.

http://docs.python.org/tut/tut.html

Best,

   Les








More information about the Python-list mailing list