【问题标题】:What is the benefit to define a function in a function in python?在 python 的函数中定义函数有什么好处?
【发布时间】:2011-10-11 02:18:38
【问题描述】:

我在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)

【问题讨论】:

    标签: python function syntax


    【解决方案1】:

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

    关于 Python 中的闭包的几点说明 - closures-in-python

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        保持隔离。它只用在这个地方。为什么要在本地使用时更全局地定义它?

        【讨论】:

        • 定义内部函数来使用闭包是很常见的,但目前的情况似乎就是你提到的情况(这也是一个很好的理由)。尔格,+1
        猜你喜欢
        • 2023-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-12
        相关资源
        最近更新 更多