嵌套函数的真实示例

3zz*_*zzy 11 python nested function

我之前询问嵌套函数是如何工作的,但遗憾的是我仍然没有得到它.为了更好地理解它,有人可以展示一些嵌套函数的实际用法示例吗?

非常感谢

Jas*_*rff 10

你的问题让我好奇,所以我查看了一些真实的代码:Python标准库.我找到了67个嵌套函数的例子.以下是一些解释.

使用嵌套函数的一个非常简单的原因就是您定义的函数不需要是全局函数,因为只有封闭函数才使用它.Python的quopri.py标准库模块的典型示例:

def encode(input, output, quotetabs, header = 0):
    ...
    def write(s, output=output, lineEnd='\n'):
        # RFC 1521 requires that the line ending in a space or tab must have
        # that trailing character encoded.
        if s and s[-1:] in ' \t':
            output.write(s[:-1] + quote(s[-1]) + lineEnd)
        elif s == '.':
            output.write(quote(s) + lineEnd)
        else:
            output.write(s + lineEnd)

    ...  # 35 more lines of code that call write in several places
Run Code Online (Sandbox Code Playgroud)

这里有一些encode函数中的常用代码,因此作者只是将其分解为一个write函数.


嵌套函数的另一个常见用途是re.sub.这是json/encode.py中的一些代码标准库模块中:

def encode_basestring(s):
    """Return a JSON representation of a Python string

    """
    def replace(match):
        return ESCAPE_DCT[match.group(0)]
    return '"' + ESCAPE.sub(replace, s) + '"'
Run Code Online (Sandbox Code Playgroud)

ESCAPE是一个正则表达式,ESCAPE.sub(replace, s)找到ESCAPEin的所有匹配项s并用其替换每个匹配项replace(match).


事实上,任何re.sub接受函数作为参数的API 都可能导致嵌套函数很方便.例如,在turtle.py中有一些愚蠢的演示代码可以做到这一点:

    def baba(xdummy, ydummy):
        clearscreen()
        bye()

    ...
    tri.write("  Click me!", font = ("Courier", 12, "bold") )
    tri.onclick(baba, 1)
Run Code Online (Sandbox Code Playgroud)

onclick 希望你传递一个事件处理函数,所以我们定义一个并传递它.

  • 这些都是很好的例子,但它们都可以作为全局函数编写而不会丢失任何功能.嵌套函数不仅仅是语法糖!你应该举一些必要的例子 (4认同)

Mr *_*ooz 8

装饰器是嵌套函数的一种非常流行的用法.这是一个装饰器的示例,它在对装饰函数的任何调用之前和之后打印语句.

def entry_exit(f):
    def new_f(*args, **kwargs):
        print "Entering", f.__name__
        f(*args, **kwargs)
        print "Exited", f.__name__
    return new_f

@entry_exit
def func1():
    print "inside func1()"

@entry_exit
def func2():
    print "inside func2()"

func1()
func2()
print func1.__name__
Run Code Online (Sandbox Code Playgroud)