学习时遇到这样段代码:
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)提供。