Detailed explanation of passing by value and passing by reference of Python functions

1. Parameter category

Formal parameter : Formal parameter for short. When defining a function, the custom parameter in parentheses after the function name is the formal parameter.
Actual parameter : Abbreviated as actual parameter, when calling a function, the parameter value passed in parentheses after the function name is the actual parameter.

2. The parameter passing method in the function

Python value transfer and reference transfer are distinguished according to the type of the actual parameter, as follows:
value transfer : refers to the actual parameter type as an immutable type (number, string, tuple);
reference transfer (or address Pass) : Refers to the fact that the actual parameter type is a variable type (list, dictionary, set collection, np matrix, torch.Tensor matrix).

The difference between passing by value and passing by reference is as follows: After the function parameter is passed by value, if the value of the formal parameter changes , the value of the actual parameter will not be affected ;
after the function parameter is passed by reference, if the value of the formal parameter changes, the value of the actual parameter will not be affected . The value of the parameter will also change together .

def fun1(num, dict_, list_):
    print('形参ID: ', id(num), id(dict_), id(list_))
    num += 1
    dict_[str(num)] = num
    list_.append(num)


if __name__ == '__main__':
    print()
    num = 1
    a = {
    
    }
    b = []
    print('原始ID: ', id(num), id(a), id(b))
    for i in range(5):
        print('实参ID: ', id(num), id(a), id(b))
        print('i:%i,\n' % i, '函数执行前 num: ', num, 'a: ', a, 'b: ', b)
        fun1(num, a, b)
        print('函数执行后 num: ', num, 'a: ', a, 'b: ', b, '\n')
        

result:

原始ID:  140715259541520 2565483473640 2565482238344
实参ID:  140715259541520 2565483473640 2565482238344
i:0,
 函数执行前 num:  1 a:  {
    
    } b:  []
形参ID:  140715259541520 2565483473640 2565482238344
函数执行后 num:  1 a:  {
    
    '2': 2} b:  [2] 

实参ID:  140715259541520 2565483473640 2565482238344
i:1,
 函数执行前 num:  1 a:  {
    
    '2': 2} b:  [2]
形参ID:  140715259541520 2565483473640 2565482238344
函数执行后 num:  1 a:  {
    
    '2': 2} b:  [2, 2] 

实参ID:  140715259541520 2565483473640 2565482238344
i:2,
 函数执行前 num:  1 a:  {
    
    '2': 2} b:  [2, 2]
形参ID:  140715259541520 2565483473640 2565482238344
函数执行后 num:  1 a:  {
    
    '2': 2} b:  [2, 2, 2] 

Guess you like

Origin blog.csdn.net/weixin_50727642/article/details/122772700