【问题标题】:Confused about this nested function对这个嵌套函数感到困惑
【发布时间】:2017-05-10 13:29:18
【问题描述】:

我正在阅读 Python Cookbook 3rd Edition,遇到了 2.6“搜索和替换不区分大小写的文本”中讨论的主题,其中作者讨论了如下嵌套函数:

def matchcase(word):
  def replace(m):
    text = m.group()
    if text.isupper():
      return word.upper()
    elif text.islower():
      return word.lower()
    elif text[0].isupper():
      return word.capitalize()
    else:
      return word
  return replace

如果我有如下文字:

text = 'UPPER PYTHON, lower python, Mixed Python'  

我在前后打印'text'的值,替换正确发生:

x = matchcase('snake')
print("Original Text:",text)

print("After regsub:", re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE))

最后一个“打印”命令显示替换正确发生,但我不确定这个嵌套函数如何“获取”:

PYTHON, python, Python

作为需要替换的词:

SNAKE, snake, Snake

内部函数replace如何获取其值'm'?
当 matchcase('snake') 被调用时,word 的值为 'snake'。
不清楚'm'的值是什么。

在这种情况下,任何人都可以帮助我清楚地理解这一点吗?

谢谢。

【问题讨论】:

    标签: function python-3.x closures nested-function


    【解决方案1】:

    当您将函数作为第二个参数传递给re.sub 时,根据the documentation

    每次出现不重叠的模式时都会调用它。该函数采用单个匹配对象参数,并返回替换字符串。

    matchcase() 函数本身返回 replace() 函数,所以当你这样做时:

    re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
    

    发生的情况是matchcase('snake') 返回replace,然后模式'python' 的每个非重叠出现作为匹配对象被传递给replace 函数作为m 参数。如果这让您感到困惑,请不要担心;这通常令人困惑。

    这是一个交互式会话,其中包含一个更简单的嵌套函数,可以让事情更清晰:

    In [1]: def foo(outer_arg):
        ...:     def bar(inner_arg):
        ...:         print(outer_arg + inner_arg)
        ...:     return bar
        ...: 
    
    In [2]: f = foo('hello')
    
    In [3]: f('world')
    helloworld
    

    所以f = foo('hello') 正在将如下所示的函数分配给变量f

    def bar(inner_arg):
        print('hello' + inner_arg)
    

    f 然后可以像这样调用f('world'),就像调用bar('world')。我希望这能让事情更清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      相关资源
      最近更新 更多