python变量传递的详细介绍

python变量传递数值

代码

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)

输出

num_1 = 123, num_2 = 123
num_1 = 123, num_2 = 0

结论

数值变量之间的是按值传递。

字符串

代码

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)

输出

str_1 = hello python, str_2 = hello python
str_1 = hello python, str_2 = hello

结论

字符串变量之间也是按值传递。

链表

代码

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)

输出

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]

结论

从上面的输出结果可以看到,l_1和l_2的作用类似于c/c++中的指针,l_2 = l_1的作用相当于l_2和l_1指向了同一块内存,内容都为[1, 2, 3, 4]。当l_2[0] = 100时,l_1中的第一个元素也被改变了。l_2 = [1,1,1]使得l_2指向了另外一块内存,也就不会对l_1的内容造成影响。

字典

代码

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)

输出

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}

结论

输出结果显示dict和list的性质一样,直接赋值时是类似于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

结论

自定义对象在赋值过程中也是按引用传递。

总结

python中数值,字符串在赋值过程中是按值传递;list、dict、对象在赋值过程中默认按引用传递,如果需要按值传递,则可以使用到copy模块下的copy和deepcopy函数。

以上就是python变量传递的详细介绍的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论