我是 Python 的新手,我对 shutil 模块中下面提到的代码片段的工作有一些疑问。
def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files"""
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns
当调用 shutil.copytree
时将 ignore
选项设置为 ignore_patterns
,然后调用 ignore_patterns
函数并返回一个函数。我的疑惑是:
1) ignore_patterns
调用时将返回 _ignore_pattern
函数引用。现在当这个函数被调用时,它如何仍然访问“模式”列表?一旦被调用的函数“ignore_patterns”返回,在其调用时创建的列表模式应该仅可用于其调用范围。
2) 返回函数_ignore_patterns
函数名中下划线的意义是什么?
最佳答案
这叫做 closure ,这是允许嵌套函数的语言的一般特征。内部函数可以关闭外部作用域中的变量,并在从外部函数外部调用时保留对该名称的引用。
下划线只是表示 _ignore_patterns
是一个内部函数,同时保持返回函数的名称相似。它可以被称为任何你喜欢的。
关于python - 从 Python 中的函数返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12160493/