在return语句中用作函数调用的python函数参数?

0yycz8jy  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(488)

因此,我在这里遇到了下面的代码,我无法理解return语句是如何工作的。 operation 是函数中的参数 sevenfive 但它在 return 声明。这里发生了什么事?
代码是:

  1. def seven(operation = None):
  2. if operation == None:
  3. return 7
  4. else:
  5. return operation(7)
  6. def five(operation = None):
  7. if operation == None:
  8. return 5
  9. else:
  10. return operation(5)
  11. def times(number):
  12. return lambda y: y * number

edit:following@chepner comment这是它们的调用方式,例如:

  1. print(seven(times(five())))
lrl1mhuk

lrl1mhuk1#

这些方法基本上允许您传递将被调用的函数对象。看这个例子

  1. def square(x):
  2. return x*x
  3. def five(operation=None):
  4. if operation is None:
  5. return 5
  6. else:
  7. return operation(5)

我现在可以打电话了 five 并通过 square 作为 operation ```

five(square)
25

展开查看全部
cld4siwp

cld4siwp2#

这里发生了什么事?
该代码利用了函数是一等公民的特性 python ,因此函数可以作为函数参数传递。这种能力不是每个人所独有的 python 语言,但如果您习惯了没有该功能的语言,那么一开始可能会令人难以置信。

相关问题