Python的函数参数是通过值传递的,但是如果变量是可变对象,返回到调用程序后,该对象会呈现被修改后的状态
测试程序如下:
# 值传递不改变变量
def addInterest(balance, rate):newBalance = balance * (1+rate)return newBalance
def test():amount = 1000rate = 0.5addInterest(amount, rate)print(amount)test()
运行结果如下:
Connected to pydev debugger (build 143.1559)
1000Process finished with exit code 0
可以发现没有改变变量amount的值,
但是我们如果传递的是列表对象,测试程序如下:
# 传递列表变量,会改变列表的值
def addInterest(balances, rate):for i in range(len(balances)):balances[i] = balances[i] * (1+rate)
def test():amounts = [1000, 105, 45, 739]rate = 0.05addInterest(amounts, rate)print(amounts)test()
运行结果如下:
Connected to pydev debugger (build 143.1559)
[1050.0, 110.25, 47.25, 775.95]Process finished with exit code 0
我们会发现函数操作改变了列表对象的值