【问题标题】:Python: can function be defined inside of another function's argument list?Python:可以在另一个函数的参数列表中定义函数吗?
【发布时间】:2011-10-10 13:12:15
【问题描述】:

有没有办法在 python 中实现这样的功能?

another_function( function(x) {return 2*x} )

【问题讨论】:

  • 这段代码有什么作用?如果调用 another_function(9)18 实际传递到 another_function 的内容是什么?

标签: python function argument-passing


【解决方案1】:

是的:

another_function( lambda x: 2*x )

需要明确:这是在调用 another_function 时发生的,而不是在定义时发生的。

【讨论】:

  • 这给了SyntaxError: invalid syntax
  • 没有错字——以为问题是关于函数定义时间的,而您的答案是函数调用时间。
  • @EthanFurman 问题完全是关于通话时间(答案被接受的事实不是敲响了警钟吗?)。作者使用了来自 Javascript 和其他基于 ecmascript 的语言的 匿名函数 语法。
  • 令人惊讶的是,并不是每个人都会说 Javascript 或其他基于 ecmascript 的语言(不幸的是,我看到接受了不好的答案);不过,我改变了我的投票。
【解决方案2】:
def another_function( function=lambda x: 2*x ):
    print(function(10))  #an example

我不确定您发布的示例代码会发生什么,但是如果您调用 another_function 显示的解决方案将调用 function(10) 并打印 20。

更重要的是,您不能调用another_function(7) 并获取14,因为7 将被分配给function7(10)' will get youTypeError: 'int' object is not callable`。

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多