简体   繁体   English

Python lambda 返回值

[英]Python lambda return value

I'm learning the lambda options to return in python and i have a question:我正在学习 lambda 选项以在 python 中返回,我有一个问题:

I need to fill the returns in this function:我需要在这个 function 中填写退货单:

def func(n):
   if n==0:
      print("finished")
   else:
      return ___
func(5)()()()()()
func(3)()()()
func(8)()()()()()()()()

The output: output:

finished
finished
finished

I thought this one is a recursive call like return func(n-1) but it doesn't work, and throws an error.我认为这是一个像 return func(n-1) 这样的递归调用,但它不起作用,并抛出错误。 Is there an option to overcome the extra empty brackets?有没有办法克服额外的空括号? count them?数他们? do something, because it should be runnable.做某事,因为它应该是可运行的。

Thanks谢谢

You're right about needing to use lambdas and func n-1, specifically关于需要使用 lambdas 和 func n-1,你是对的,特别是

return lambda: func(n-1)

This returns a lambda that doesn't need any parameters passed in, to handle the brackets, and the return of the is the function being called with n-1, which in most calls you're making, is returning the next lambda function call这将返回一个 lambda,它不需要传入任何参数来处理括号,并且返回的是 function 被 n-1 调用,在您进行的大多数调用中,它返回下一个 lambda function 调用

The operator () is the function call. operator()是function的调用。 So for example:例如:

def foo():
   print('Foo executed')

def bar():
   # We return the foo FUNCTION itself, without calling it.
   return foo

In the above code, if you execute foo() , it'll print "Foo executed".在上面的代码中,如果你执行foo() ,它会打印“Foo executed”。 But if you execute bar() , it will return foo , which is the function. So you can execute bar()() , where the first () is executing the function bar, returning foo, and then with the second (), you call the returned foo function.但是如果你执行bar() ,它会返回foo ,也就是 function。所以你可以执行bar()() ,其中第一个 () 执行 function bar,返回 foo,然后与第二个 (),你调用返回的 foo function。

Edit: When I typed it, you removed the what are those bunch of () because they are new to you... But I just leave it there maybe it'll help.编辑:当我输入它时,你删除了那些 () 是什么,因为它们对你来说是新的......但我只是把它留在那里也许它会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM