python--回调函数

学习时遇到这样段代码:

import re
text = 'UPPER PYTHON, lower python, Mixed Python'
def replace(m,word):
    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

print(re.sub(r'python',replace('snack'),text,flags=re.IGNORECASE))  

其中
函数的用法没有看懂--调用时为什么少传递了一个参数(m)呢?原来,这叫做回调函数,在调用回调函数时,调用函数(re.sub)会先向回调函数(replace)传递一些数据。为了方便理解,我们先来看一个更简单的例子:

def f(x):
    return x**2
def g(x,f):
    return f(x)
print(g(5,f))

在这个例子中,回调函数为f(),调用函数为个g()。我们可以看到,g()在调用f()时,会先向其传递属于g()自己的一个参数(x)。因此,在最终调用(打印)g()函数时,并不需要再为其内部的f()传递参数。换言之,向回调函数传递参数的工作由调用函数(部分)代劳了。

在回调的过程中,向回调函数传递怎样的信息取决于调用函数的内部实现。对于g(),它只做了一点微小的工作--向f()传递一个实数x。对于我们开头看到的函数re.sub(),情况则要复杂一些。先来看看文档:

sub(pattern, repl, string, count=0, flags=0):
    """Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  <strong>repl can be either a string or a callable</strong>;
    if a string, backslash escapes in it are processed. <strong> If it is
    a callable, it's passed the match object and must return
    a replacement string to be used</strong>."""

如果第二个参数是callable,那么re.sub向回调函数(replace)传递的是一个re.match对象,而re.match函数所需要的两个参数(正则匹配式,匹配文本)分别由re.sub()内部的pattern(r'python')、string(text)提供。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值