1.

Which type of function calling mechanism is employed in Python? Call by value or Call by reference?

Answer»

Calling a function by value is found to be USED in C/C++ where a variable is actually a named location in computer memory. Hence the passed expression is copied into the formal argument which happens to be a local variable of the CALLED function. Any manipulation of that local variable doesn’t affect the variable that was actually passed.

The following C PROGRAM has square() function. It is called from the main by passing x which is copied to the local variable in square(). The change inside called function doesn’t have impact on x in main()

#include <stdio.h> int main() {    int square(int); int x=10; printf("\nx before passing: %d",x); square(x); printf("\nx after passing: %d",x); } int square(int x) { x=x*x; } result: x before passing: 10 x after passing: 10

In Python though, a variable is just a label of an object in computer memory. Hence formal as well as actual argument variables in fact are two different labels of same object – in this case 10. This can be verified by id() function.

>>> def square(y): print (id(y)) >>> x=10 >>> id(x) 94172959017792 >>> square(x) 94172959017792

Hence we can infer that Python calls a function by passing reference of actual arguments to formal arguments. However, what happens when the function manipulates the received object depends on the type of object.

When a function makes modifications to the immutable object received as an argument,  changes do not reflect in the object that was passed.

>>> def square(y): print ('received',id(y)) y=y**2 print ('changed',id(y),'y=',y) >>> x=10 >>> id(x) 94172959017792 >>> square(x) received 94172959017792 changed 94172959020672 y= 100 >>> x 10

It can be seen that x=10 is passed to the square() function. Inside, y is changed. However, y becomes a label of another object 100, which is having different id(). This change doesn’t reflect in x – it being an immutable object. The same thing happens to a string or tuple.

However, if we PASS a MUTABLE object, any changes by called function will also have effect on that object after returning from the function.

In the example below, we pass a list (it is a mutable object) to a function and then add some more elements to it. After returning from the function, the original list is found to be modified.

>>> def newlist(list): print ('received', list, id(list)) list.append(4) print ('changed', list, id(list)) >>> num=[1,2,3] >>> id(num) 139635530080008 >>> newlist(num) received [1, 2, 3] 139635530080008 changed [1, 2, 3, 4] 139635530080008 >>> num [1, 2, 3, 4]

Hence we can say that a mutable object, passed to a function by reference gets modified by any changes inside the called function.



Discussion

No Comment Found