[英]how to get an argument from an outer function? python
I would like to create a function with one string argument.我想用一个字符串参数创建一个函数。 This function should return an anonymous function that checks if the function argument is equal to the argument of the external function.此函数应返回一个匿名函数,该函数检查函数参数是否等于外部函数的参数。 But I do not understand how to get the argument of an external function.但我不明白如何获得外部函数的参数。
def create(arg):
outer =
return lambda a: outer == arg
firstValue = create("secret")
print(firstValue("secret")) # >> True
print(firstValue("SECRET")) # >> False
def create(arg):
return lambda a: a == arg # replace outer with a
firstValue = create("secret")
print(firstValue("secret")) # >> True
print(firstValue("SECRET")) # >> False
Edit: (for explanation)编辑:(用于解释)
The first function, create("secret")
, takes as argument arg = "secret"
.第一个函数create("secret")
将arg = "secret"
作为参数。 Following the execution of its body, it creates the other lambda function that takes as argument a
and compares it to "secret"
;在执行其主体之后,它创建另一个 lambda 函数,该函数将参数a
作为参数并将其与"secret"
进行比较; that function is returned.该函数被返回。 Again, remember that the function that is being returned is a function that takes one parameter a
and compares it to the value "secret"
;再次记住,返回的函数是一个函数,它接受一个参数a
并将其与值"secret"
进行比较; it's as if you just did manually this:就好像您只是手动执行此操作:
def anonymous(a):
return a == "secret"
That's the function that is returned.这就是返回的函数。 Now you are assigning this returned function to the name firstValue
;现在您将此返回的函数分配给名称firstValue
; it's as if you are doing this: firstValue = anonymous
.就好像你在这样做: firstValue = anonymous
。
Finally you are just calling THIS function with argument a="secret"
or a="SECRET"
, which obviously returns True
in the first case and False
in the second.最后,您只是使用参数a="secret"
或a="SECRET"
调用此函数,显然在第一种情况下返回True
,在第二种情况下返回False
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.