在python中定义函数的功能有什么好处?

Auf*_*ind 30 python syntax function

我在effbot上遇到了这段python代码(粘贴在下面),我想知道:

为什么在函数中定义函数?

import re, htmlentitydefs

##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("(?s)<[^>]*>|&#?\w+;", fixup, text)
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 69

为什么在函数中定义函数?

保持孤立.它只用在这一个地方.为什么在本地使用时更全面地定义它?


Joh*_*Jr. 7

这只是将大型函数分解为更小的部分而不用另一个函数名称污染全局命名空间的另一种方法.内部函数通常不是独立函数,因此不能正确地属于全局命名空间.


Rom*_*huk 6

这种代码的主要原因通常是函数闭包.它是强大的东西,不仅适用于Python.例如,JavaScript从中获益良多.

关于Python中的闭包的一些观点 - 在python中的闭包.