Home > Article > Backend Development > Detailed introduction to python variable passing
Code
num_1 = 123 num_2 = num_1 # 改变num_2值前 print 'num_1 = {0}, num_2 = {1}'.format(num_1, num_2) num_2 = 0 # 改变num_2值后 print 'num_1 = {0}, num_2 = {1}'.format(num_1, num_2)
Output
num_1 = 123, num_2 = 123 num_1 = 123, num_2 = 0
Conclusion
Numeric variables are passed by value.
Code
str_1 = 'hello python' str_2 = str_1 # 改变str_2值前 print 'str_1 = {0}, str_2 = {1}'.format(str_1, str_2) str_2 = 'hello' # 改变str_2值后 print 'str_1 = {0}, str_2 = {1}'.format(str_1, str_2)
Output
str_1 = hello python, str_2 = hello python str_1 = hello python, str_2 = hello
Conclusion
String variables are also passed by value.
Code
l_1 = [1, 2, 3, 4] l_2 = l_1 print 'l_1 = {0}, l_2 = {1}'.format(l_1, l_2) l_2[0] = 100 # 改变l_2的第一个元素 print 'l_1 = {0}, l_2 = {1}'.format(l_1, l_2) l_2 = [1,1,1] # 改变l_2的全部元素 print 'l_1 = {0}, l_2 = {1}'.format(l_1, l_2)
Output
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]
Conclusion
As you can see from the above output, the functions of l_1 and l_2 are similar to pointers in c/c++, and the function of l_2 = l_1 It is equivalent to l_2 and l_1 pointing to the same memory, and the contents are [1, 2, 3, 4]. When l_2[0] = 100, the first element in l_1 is also changed. l_2 = [1,1,1] makes l_2 point to another piece of memory, which will not affect the content of l_1.
Code
d_1 = {'a': 1, 'b': 2, 'c': 3} d_2 = d_1 print 'd_1 = {0}, d_2 = {1}'.format(d_1, d_2) d_2['c'] = 10 print '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)
Output
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}
Conclusion
The output shows that dict and list have the same properties. Direct assignment is similar to passing by reference in C++ .
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_1 print 'p_1: {0}; p_2: {1}'.format(p_1, p_2) p_2.x = 122 print '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 = 34 p_1: x = 122 y = 34; p_2: x = 122 y = 34 p_1: x = 122 y = 34; p_2: x = 89 y = 978
functions under the copy module.
The above is the detailed content of Detailed introduction to python variable passing. For more information, please follow other related articles on the PHP Chinese website!