Laszlo Zsolt Nagy
gandalf at designaproduct.biz
Thu Sep 22 19:09:25 CEST 2005
> 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.
So if you really want to create a function with a side effect, do
something like this:
>>> a1 = 
>>> a2 = 
>>> def f(x):
... if x is a1:
... a1 += 1
... elif x is a2:
... a2 += 1
But please note that having side effect is generally considered harmful.
Please read the tutorial, these things are explained quite well.
More information about the Python-list