Python 2.7 中的多参数简易函数
我正在学习Zelle的Python编程,但在函数这部分遇到了一些困难。
我们有这个代码:
def addInterest(balance, rate):
newBalance = balance * (1+rate)
balance = newBalance
def test():
amount = 1000
rate = 0.05
addInterest(amount, rate)
print amount
test()
这个代码没有输出1050,但下面的代码成功了:
def addInterest(balance, rate):
newBalance = balance * (1+rate)
return newBalance
def test():
amount = 1000
rate = 0.05
amount = addInterest(amount, rate)
print amount
test()
这两段代码的细微差别在于addInterest函数的第三行。Zelle对此有解释,但我还没有完全理解。你能帮我解释一下为什么第一段代码几乎一模一样却没有第二段代码的效果吗?
3 个回答
0
关键字是 return
。这个词的意思就是从一个函数里把一个值返回给一个变量(在你的第二段代码里,这个变量是 amount
)。
在第一段代码中,你没有返回任何东西,这就是为什么 print amount
的结果不是你想要的样子。
在你的第二段代码中,你是把 newBalance
的值返回了。现在,变量 amount
和函数里的 newBalance
是一样的值。
所以在你的第一段代码中,调用 addInterest(amount, rate)
是没有任何作用的。因为它没有返回任何东西,所以没有用。而你在第二个函数里做的事情是正确的。
0
去看看这个问题的精彩回答:如何通过引用传递变量?
self.variable = 'Original'
self.Change(self.variable)
def Change(self, var):
var = 'Changed'
3
这是因为你在 addInterest
函数里面修改的 balance
对象,并不是你传给这个函数的 amount
对象。简单来说,你只是修改了传入函数的那个对象的本地副本,所以原来的对象的值没有变。如果你在你的 Python 环境中运行下面的代码,就能看到这一点:
>>> def addInterest(balance, rate):
... print (balance)
... newBalance = balance * (1 + rate)
... balance = newBalance
...
>>> amount = 1000
>>> rate = 0.05
>>> print id(amount)
26799216
>>> addInterest(amount, rate)
1000
>>>
这里的 id
函数可以返回一个对象的身份标识,这个标识可以用来判断两个对象是否是同一个。