在python中定义函数的好处是什么? [英] What is the benefit to define a function in a function in python?

查看:686
本文介绍了在python中定义函数的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  import re,htmlentitydefs 

##
#从文本字符串中删除HTML或XML字符引用和实体。

#@param text HTML(或XML)源文本。
#@return必要时将纯文本作为Unicode字符串。

def unescape(text):
def fixup(m):
text = m.group(0)
if text [:2] ==& amp ;#:
#字符引用
尝试:
if text [:3] ==& #x:
return unichr(int(text [3: - 1],16))
else:
返回unichr(int(text [2:-1]))
除ValueError:
传递
else:
$命名实体
尝试:
text = unichr(htmlentitydefs.name2codepoint [text [1:-1]])
除了KeyError:
传递
返回文本#保留原样
return re.sub((?s)< [^> *> |&#?\w +;,fixup,text)
>

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


I encountered this piece of python code (pasted below) on effbot and I was wondering:

Why defining a function within a function?

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)

解决方案

Why defining a function within a function?

To keep it isolated. It's only used in this one place. Why define it more globally when it's used locally?

这篇关于在python中定义函数的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆