开发者

Python: can function be defined inside of another function's argument list?

开发者 https://www.devze.com 2023-04-12 03:58 出处:网络
Is there a way to achieve something like thi开发者_开发技巧s in python? another_function( function(x) {return 2*x} )

Is there a way to achieve something like thi开发者_开发技巧s in python?

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


Yes:

another_function( lambda x: 2*x )

To be clear: this is taking place when another_function is called, not when it is defined.


def another_function( function=lambda x: 2*x ):
    print(function(10))  #an example

I'm not sure what happens with the example code you posted, but with the solution shown if you call another_function it will call function(10) and print 20.

More to the point, you cannot call another_function(7) and get 14 because 7 will get assigned to function and 7(10)' will get youTypeError: 'int' object is not callable`.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号