问题描述
我想知道如何在另一个函数内部访问一个函数。
我看到了这样的代码:
I am wondering how I can access a function inside another function.I saw code like this:
>>> def make_adder(x):
def adder(y):
return x+y
return adder
>>> a = make_adder(5)
>>> a(10)
15
那么,还有另外一种方法可以调用加法器
函数?我的第二个问题是为什么在最后一行我称之为加法器
不是加法器(...)
?
So, is there another way to call the adder
function? And my second question is why in the last line I call adder
not adder(...)
?
好的解释非常值得赞赏。
Good explanations are much appreciated.
推荐答案
不,你不能打电话因为它是一个局部变量,因此它是 make_adder
。
No, you can't call it directly as it is a local variable to make_adder
.
您需要使用加法器()
,因为返回加法器
在调用<$ c $时返回函数对象加法器
C> make_adder(5)。要执行这个函数对象,你需要()
You need to use adder()
because return adder
returned the function object adder
when you called make_adder(5)
. To execute this function object you need ()
def make_adder(x):
def adder(y):
return x+y
return adder
...
>>> make_adder(5) #returns the function object adder
<function adder at 0x9fefa74>
在这里,您可以直接调用它,因为它可以访问它,因为它是由函数返回的 make_adder
。返回的对象实际上称为,因为即使尽管函数 make_addr
已经返回,但它返回的函数对象 adder
仍然可以访问变量 X
。在py3.x中,您还可以使用 nonlocal
语句来修改 x
的值。
Here you can call it directly because you've access to it, as it was returned by the function make_adder
. The returned object is actually called a closure because even though the function make_addr
has already returned, the function object adder
returned by it can still access the variable x
. In py3.x you can also modify the value of x
using nonlocal
statement.
>>> make_adder(5)(10)
15
Py3.x示例:
>>> def make_addr(x):
def adder(y):
nonlocal x
x += 1
return x+y
return adder
...
>>> f = make_addr(5)
>>> f(5) #with each call x gets incremented
11
>>> f(5)
12
#g gets it's own closure, it is not related to f anyhow. i.e each call to
# make_addr returns a new closure.
>>> g = make_addr(5)
>>> g(5)
11
>>> g(6)
13
这篇关于如何访问函数内部的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!