Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python函数中定义函数有什么好处?_Python_Function_Syntax - Fatal编程技术网

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

在python函数中定义函数有什么好处?,python,function,syntax,Python,Function,Syntax,我在上遇到了这段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 nece

我在上遇到了这段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)
import re,htmlentitydefs
##
#从文本字符串中删除HTML或XML字符引用和实体。
#
#@param text HTML(或XML)源文本。
#@如有必要,以Unicode字符串形式返回纯文本。
def unescape(文本):
def固定(m):
text=m.group(0)
如果文本[:2]=”&#“:
#字符引用
尝试:
如果文本[:3]=“&#x”:
返回unichr(int(文本[3:-1],16))
其他:
返回unichr(int(文本[2:-1]))
除值错误外:
通过
其他:
#命名实体
尝试:
text=unichr(htmlentitydefs.name2codepoint[text[1:-1]]
除KeyError外:
通过
返回文本#保持原样
返回re.sub(“(?s)]*>|和#?\w+;”,修正,文本)
为什么要在函数中定义函数


把它隔离起来。它只在这一个地方使用。当它在本地使用时,为什么要更全局地定义它?

这只是另一种方法,可以将一个大函数分解成更小的部分,而不会用另一个函数名污染全局名称空间。通常,内部函数不是独立的,因此不属于全局名称空间。

此类代码的主要原因通常是函数。这是一个强大的东西,不仅适用于Python。例如,JavaScript从中获益匪浅


关于Python中闭包的一些要点-。

定义内部函数以使用闭包是很常见的,但目前的情况似乎就是您提到的(这也是一个很好的理由)。因此,+1