2024-10-04 09:19:50 发布
网友
我想把一个函数传递给另一个函数,但是在第一个函数中使用第二个函数的作用域。我有javascript背景,所以我习惯于这样做:
function write(str, path) { // do stuff } function doThis(fn) { fn() } function doThisString(str, path) { doThis(function() { write(str, path) }); }
如何在python中执行此操作
是的,Python支持闭包。但是除了非常有限的(只有一个表达式)lambda形式之外,函数在使用之前必须在单独的语句中定义-它们不能在表达式中创建
lambda
如果为了避免嵌套而要避免嵌套函数定义,可以使用functools.partial。无论如何,您的具体示例将大大简化:
functools.partial
from functools import partial def doThisString(str, path): doThis(partial(write, str, path))
结果并不总是那么好,所以有时候有更好的选择
下面是它在python中的语法形式:
def write(text, path): // do stuff def doThis(fn): fn() def doThisString(text, path): doThis(lambda: write(text, path) )
python的等价物是
def write (mystr, path): pass def doThis (f): f () def doThisString (mystr, path): doThis (lambda: write (mystr, path) )
或者:
def doThisString (mystr, path): def function (): write (mystr, path) doThis (function)
是的,Python支持闭包。但是除了非常有限的(只有一个表达式)
lambda
形式之外,函数在使用之前必须在单独的语句中定义-它们不能在表达式中创建如果为了避免嵌套而要避免嵌套函数定义,可以使用
functools.partial
。无论如何,您的具体示例将大大简化:结果并不总是那么好,所以有时候有更好的选择
下面是它在python中的语法形式:
python的等价物是
或者:
相关问题 更多 >
编程相关推荐