Fourth, the function pass-by-value problem
Let's look at an example:
# -*- coding: UTF-8 -*-
def chagne_number( b ):
b = 1000
b = 1
chagne_number(b)
print( b )
The final output is:
1
chagne_number
not ?In Python, strings, integers, floats, tuples are immutable objects, while list, dict, etc. are objects that can be changed.
a = 1
, in fact, is to generate an integer object 1, and then the variable a points to 1, when a = 1000
in fact is to generate another integer object 1000, and then change the point of a, no longer points to the integer object 1, but points to 1000, The last 1 will be discardeda = [1,2,3,4,5,6]
is to generate an object list, there are 6 elements in the list, and the variable a points to the list, it a[2] = 5
is to change the value of the third element of the list a, which is different from the above, not the a redirects to, but directly modifies the value of the element in the list.Immutable types: C++-like passing by value, such as integers, strings, tuples. Such as fun(a), only the value of a is passed, and the a object itself is not affected. For example, modifying the value of a inside fun(a) only modifies another copied object and does not affect a itself.
Changeable types: C++-like pass-by-reference, such as lists, dictionaries. For example, fun(a) means that a is really passed, and the a outside of fun will also be affected after the modification.
Therefore, in the first example, b = 1
, creates an integer object 1, and the variable b points to this object, and then when the function chagne_number is passed, the variable b is copied by value, and only the value of b is passed, and it has no effect to b itself. For details, you can look at the modified example for a better understanding through the printed results.
# -*- coding: UTF-8 -*-
def chagne_number( b ):
print('函数中一开始 b 的值:{}' .format( b ) )
b = 1000
print('函数中 b 赋值后的值:{}' .format( b ) )
b = 1
chagne_number( b )
print( '最后输出 b 的值:{}' .format( b ) )
The result printed:
函数中一开始 b 的值:1
函数中 b 赋值后的值:1000
最后输出 b 的值:1
Of course, if the parameter is a changeable type, after calling this function, the original value will also be changed. The specific example is as follows:
# -*- coding: UTF-8 -*-
def chagne_list( b ):
print('函数中一开始 b 的值:{}' .format( b ) )
b.append(1000)
print('函数中 b 赋值后的值:{}' .format( b ) )
b = [1,2,3,4,5]
chagne_list( b )
print( '最后输出 b 的值:{}' .format( b ) )
The result of the output:
函数中一开始 b 的值:[1, 2, 3, 4, 5]
函数中 b 赋值后的值:[1, 2, 3, 4, 5, 1000]
最后输出 b 的值:[1, 2, 3, 4, 5, 1000]
Featured Article Recommendations
Follow me and catch the latest and most trendy black technology together