在另一个函数中引用函数的作用域

2024-10-04 09:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个函数传递给另一个函数,但是在第一个函数中使用第二个函数的作用域。我有javascript背景,所以我习惯于这样做:

function write(str, path) {
    // do stuff
}

function doThis(fn) {
    fn()
}

function doThisString(str, path) {
    doThis(function() {
      write(str, path)
    });
}

如何在python中执行此操作


Tags: path函数functionjavascript作用域dowritefn
3条回答

是的,Python支持闭包。但是除了非常有限的(只有一个表达式)lambda形式之外,函数在使用之前必须在单独的语句中定义-它们不能在表达式中创建

如果为了避免嵌套而要避免嵌套函数定义,可以使用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)

相关问题 更多 >