[英]Functions can return another function use in Python
It's not hard to understand "functions are objects we can return a function from another function".不难理解“函数是我们可以从另一个函数返回 function 的对象”。 But how is below code working?但是下面的代码是如何工作的?
# Functions can return another function
def create_adder(x):
def adder(y):
return x+y
return adder
add_15 = create_adder(15)
print (add_15(10))
The result is 25.结果是 25。
Personal understanding:个人理解:
create_adder(x)
function will return the reference of adder
function, kind like: create_adder(x)
function 将返回adder
function 的引用,类似于:
<function create_adder.<locals>.adder at 0x7fd83e19fe18>
15 is x in it(create_adder) and add_15 is object of create_adder function, so add_15(10) might have taken x as the argument.Then how did it get the value of y?No variable created for it and no argument passed for it? 15是其中的x(create_adder),add_15是create_adder function的object,所以add_15(10)可能将x作为参数。那么它是如何得到y的值的?没有为它创建变量并且没有为它传递参数?
Can someone help me point out the misunderstanding?有人可以帮我指出误解吗?
A couple more comments should make it clear:还有一些评论应该清楚:
# Functions can return another function
def create_adder(x):
def adder(y):
return x+y
return adder
add_15 = create_adder(15)
# def create_adder(15):
# def adder(y):
# return 15+y
# return adder
print (add_15(10))
# add_15(10) = adder(10)
# adder(10) # returns 15 + 10 = 25
add_15 = create_adder(15) add_15 = create_adder(15)
-----> here, x will be assigned as 15 and create_adder(15) will have the address of adder function -----> 这里,x 将被分配为 15,create_adder(15) 将具有加法器的地址 function
print (add_15(10)) -----> that address will be passed here to assign 10 to y, where already x is having value of 15, and x+y ie 25 will be returned print (add_15(10)) -----> 该地址将被传递到这里以将 10 分配给 y,其中 x 的值已经是 15,并且 x+y 即 25 将被返回
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.