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)
找到ESCAPE
in的所有匹配项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
希望你传递一个事件处理函数,所以我们定义一个并传递它.
装饰器是嵌套函数的一种非常流行的用法.这是一个装饰器的示例,它在对装饰函数的任何调用之前和之后打印语句.
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)
归档时间: |
|
查看次数: |
4663 次 |
最近记录: |