从函数中返回函数

其实并不需要在一个函数里去执行另一个函数,我们也可以将其作为输出返回出来:

  1. def hi(name="yasoob"):
  2. def greet():
  3. return "now you are in the greet() function"
  4. def welcome():
  5. return "now you are in the welcome() function"
  6. if name == "yasoob":
  7. return greet
  8. else:
  9. return welcome
  10. a = hi()
  11. print(a)
  12. #outputs: <function greet at 0x7f2143c01500>
  13. #上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
  14. #现在试试这个
  15. print(a())
  16. #outputs: now you are in the greet() function

再次看看这个代码。在if/else语句中我们返回greetwelcome,而不是greet()welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

你明白了吗?让我再稍微多解释点细节。

当我们写下a = hi()hi()会被执行,而由于name参数默认是yasoob,所以函数greet被返回了。如果我们把语句改为a = hi(name = "ali"),那么welcome函数将被返回。我们还可以打印出hi()(),这会输出now you are in the greet() function