首页 > Python外层函数返回嵌套函数这种写法有什么意义?

Python外层函数返回嵌套函数这种写法有什么意义?

有这样一个函数:

class Handler:
    def sub(self, name):
        def substitution(match):
            result = self.callback('sub_', name, match)
            if result is None: match.group(0)
            return result
        return substitution

调用方式应该是Handler.sub(name)(match),如果我改成这样:

class Handler:
    def sub(self, name, match):
        result = self.callback('sub_', name, match)
        if result is None: match.group(0)
        return result

调用方式变成Handler.sub(name,match),效果应该是一样的。那为什么非要写成嵌套函数的形式呢?

PS:代码来自《Python基础教程》第20章——项目1:即时标记,中文版p327,英文版p410


书中后面有解释:供其他以函数为参数的函数使用。

鄙人读书不细致,多次自问自答,大家见笑。

【热门文章】
【热门文章】