This article describes how to pass python variables in detail.
Num_1 = 123num_2 = num_1 # print 'Num _ 1 = {0}, num_2 = {1} 'before changing the num_2 value }'. format (num_1, num_2) num_2 = 0 # print 'Num _ 1 = {0}, num_2 = {1} 'after changing the num_2 value }'. format (num_1, num_2)
num_1 = 123, num_2 = 123num_1 = 123, num_2 = 0
Values are passed by value.
String
Str_1 = 'Hello Python' str _ 2 = str_1 # print 'Str _ 1 = {0}, str_2 = {1} 'before changing the str_2 value }'. format (str_1, str_2) str_2 = 'hello' # print 'Str _ 1 = {0}, str_2 = {1} 'after the str_2 value is changed }'. format (str_1, str_2)
str_1 = hello python, str_2 = hello pythonstr_1 = hello python, str_2 = hello
String variables are also passed by value.
Linked list
L_1 = [1, 2, 3, 4] l_2 = l_1print 'L _ 1 = {0}, l_2 = {1 }'. format (l_1, l_2) l_2 [0] = 100 # Change the first element of l_2 print 'L _ 1 = {0}, l_2 = {1 }'. format (l_1, l_2) l_2 = [, 1] # Change all elements of l_2 print 'L _ 1 = {0}, l_2 = {1 }'. format (l_1, l_2)
l_1 = [1, 2, 3, 4], l_2 = [1, 2, 3, 4]l_1 = [100, 2, 3, 4], l_2 = [100, 2, 3, 4]l_1 = [100, 2, 3, 4], l_2 = [1, 1, 1]
From the above output, we can see that the functions of l_1 and l_2 are similar to pointers in c/c ++. the functions of l_2 = l_1 are equivalent to that of l_2 and l_1 pointing to the same memory, the content is [1, 2, 3, 4]. When l_2 [0] = 100, the first element in l_1 is also changed. L_2 = [, 1] causes l_2 to point to another memory and will not affect the content of l_1.
Dictionary
d_1 = {'a': 1, 'b': 2, 'c': 3}d_2 = d_1print 'd_1 = {0}, d_2 = {1}'.format(d_1, d_2)d_2['c'] = 10print 'd_1 = {0}, d_2 = {1}'.format(d_1, d_2)d_2 = {'e': 12, 'f': 15}print 'd_1 = {0}, d_2 = {1}'.format(d_1, d_2)
d_1 = {'a': 1, 'c': 3, 'b': 2}, d_2 = {'a': 1, 'c': 3, 'b': 2}d_1 = {'a': 1, 'c': 10, 'b': 2}, d_2 = {'a': 1, 'c': 10, 'b': 2}d_1 = {'a': 1, 'c': 10, 'b': 2}, d_2 = {'e': 12, 'f': 15}
The output result shows that dict and list are of the same nature. direct value assignment is similar to transfer by reference in c ++.
Object
class Point: def init(self, x, y): self.x = x self.y = y def str(self): return ''.join(['x = ', str(self.x), ' ', 'y = ', str(self.y)])p_1 = Point(12,34)p_2 = p_1print 'p_1: {0}; p_2: {1}'.format(p_1, p_2)p_2.x = 122print 'p_1: {0}; p_2: {1}'.format(p_1, p_2)p_2 = Point(89, 978)print 'p_1: {0}; p_2: {1}'.format(p_1, p_2)
p_1: x = 12 y = 34; p_2: x = 12 y = 34p_1: x = 122 y = 34; p_2: x = 122 y = 34p_1: x = 122 y = 34; p_2: x = 89 y = 978
Custom objects are also passed by reference during the value assignment process.
Summary
In Python, values are transmitted by value during the value assignment process. in list, dict, and object assignment, values are transmitted by reference by default. if values are required, you can use the copy and deepcopy functions in the copy module.
The above is a detailed introduction to python variable passing. For more information, see other related articles in the first PHP community!