The difference between python function parameters is an old story

  • 2020-06-03 07:03:19
  • OfStack

In the process of using python, it is found that when the function parameter is list, calling list. append() inside the function will change the form parameter, which is not quite like that of C/C++. Please refer to relevant data and record 1 here.

id in python can get the memory address of an object


>>> num1 = 10
>>> num2 = num1
>>> num3 = 10
>>> id(num1)
>>> id(num2)
>>> id(num3)

It can be seen that the 33 objects of num1, num2 and num33 point to 1 address. python USES a method called reference counting to complete here, which is very similar to the smart pointer of C++zhong. Assigning variables to variables is equivalent to the reference counter +1 with 1 object, instead of reallocating space.

For the list object, you can see the following results:


>>> list1 = [0,1]
>>> list2 = [0,1]
>>> id(list1)
>>> id(list2)
>>> list3 = list1
>>>id(list3)

list1 and list3 point to the same space, and list2 to another address.

In python, function parameter passing is object passing, but there are also local and global problems. There are two rules in the process of parameter passing:

Copying parameters by reference to locally scoped objects means that the variable used to access function parameters is independent of the object being raised to the function, as there is a replication problem, which is the same as in C. And modifying local objects does not change the original data.

Mutable objects can be modified in place. Mutable objects are mostly lists and dictionaries, and the proper place is essentially the local child object that I analyzed earlier that does not change the dictionary object or ID of the list object


def incrInt(num):
  pId(num)
  num += 1;
  pId(num)

def incrList(listArg):
  pId(listArg)
  listArg.append(1);
  pId(listArg)
def pId(arg):
  print id(arg)
num1 = 10
pId(num1)
incrInt(num1)
print(num1)

list1 = [0,2]
pId(list1)
incrList(list1)
print(list1)

The results are as follows:


python test.py
4299181904
10
4336979912
[0, 2, 1]

You can see inside the function that by changing the value of int, num points to another block of memory address, while changing list points to the same block of memory address.

In python, objects can be divided into variable (mutable) and immutable (immutable). Tuples (tuple), numeric types (number), and strings (string) are immutable objects, while objects of characters (dictionary) and lists (list) are mutable objects.

So you have to pay attention to that as you go through.


Related articles: