Object passing in python function

In python, objects can be divided into immutable types and mutable types.

Immutable types: including strings, integers, tuples and other types, similar to value transfer in C++.

Variable type: includes lists, dictionaries and other types, similar to reference passing in C++.

An example of passing an immutable type object is as follows:

#!/usr/bin/env python
# -*- coding:utf-8 -*-


def test_func(a):
    a = 10


if __name__ == '__main__':
    a = 5
    test_func(a)
    print(a)

output:

5

Since a is an integer and an immutable type, the output result is 5.

An example of passing mutable type objects is as follows:

#!/usr/bin/env python
# -*- coding:utf-8 -*-


def test_func(a):
    a.append(5)


if __name__ == '__main__':
    a = [1, 2, 3, 4]
    test_func(a)
    print(a)

output:

[1, 2, 3, 4, 5]

Since a is a list and is a mutable type, the output result is [1, 2, 3, 4, 5].

Guess you like

Origin blog.csdn.net/kevinjin2011/article/details/129405623