Parameter passing of the Python function:
Immutable types: Values such as C + + are passed, such as integers, strings, and tuples.
such as fun (a), passing only a value, does not affect the A object itself.
For example, in Fun (a) to modify the value of a, just modify another copy of the object, does not affect the a itself.
mutable types: References such as C + + are passed, such as lists, dictionaries.
such as Fun (LA), is the real transfer of LA, the modified fun outside of LA will also be affected
Everything in Python is an object, strictly meaning we can't say value passing or reference passing, we should say immutable objects and pass mutable objects.
Python-Passed immutable object instance:
# !/usr/bin/python3 def # There is no relationship between a and the next line of a, just represents the value of the function input parameter, is an object is not a variable name a = ten# here produces a function inside the variable A and assigns the value B = 2changeint (b)print# result is 2
passing a Mutable object instance
A mutable object modifies a parameter in a function, and the original parameter is changed in the function that calls the function. For example:
#!/usr/bin/python3 #Writable Function DescriptiondefChangeme (mylist):#The mylist here is the list object corresponding to the function input parameter, which can be changed by the value of the column table . "to modify an incoming list"Mylist.append ([1,2,3,4]) #修改列表里的值 Print("value in function:", MyList)return #Call the Changeme functionMyList = [10,20,30]changeme (mylist)Print("values outside the function:", MyList)
The object that passes in the function and adds new content at the end is the same reference, which is the list object. So the output is as follows:
Value in function: [10, 20, 30, [1, 2, 3,4] out-of-function values: [10 , 20, 30, [1 2, 3 , 4] [
Python functions passing mutable immutable objects