Python 中的參數(shù)傳遞模式是共享傳參
def add(a, b):
a += b
return a
x = 1
y = 2
//調(diào)用加法
add(a, b)
print(a)//此時輸出的值為1
如果可變對象作為默認(rèn)值的話,會導(dǎo)致一些問題
class List:
def __init__(self, list = []):
self.list = list
a = List()
b = List()
a.list// -> []
b.list// -> []
a.list.append(1)
a.list// -> [1]
b.list// -> [1]
//此時b 跟 a 引用了同一個列表
建議不要使用可變類型作為參數(shù)的默認(rèn)值
如何解決上面的問題?
class List:
def __init(self, list = None):
if list is None:
self.list = []
else:
self.list = list