本专栏会不定期增加一些Python基本问题的分析和解答以促进Python知识的理解和掌握。第一道Python题如下:
#第一题Python题
a = 1
def fun(a):
a = 2
fun(a)
print(a)
b = []
def fun(b):
b.append(1)
fun(b)
print(b)
这道题a与b的输出是什么?我们不妨先把其中的地址打印出来:
#Problem#1
a = 1
def fun(a):
print(str(id(a)))
a = 2
print(str(id(a))+":"+str(id(2)))
fun(a)
print(str(id(a))+":"+str(a))
b = []
def fun(b):
print(str(id(b)))
b.append(1)
print(str(id(b))+":"+str(id(1)))
fun(b)
print(str(id(b))+":"+str(b))
输出结果为:
1355046512
1355046528:1355046528
1355046512:1
46538224
46538224:1355046512
46538224:[1]
从地址中可以看到,a的地址发生了变化,其实a传入的是复制的引用值,存储的是数字的地址,由于是值传递,所以实际值并没有改变,b为列表,传入的是实际的地址,所以值发生了改变。