是否可以将方法作为函数参数传递?
在学习正则表达式以及如何使用它们时,我决定尝试创建一个函数,我可以使用所使用的不同正则表达式方法反复调用该函数:
def finder (regex, query, method):
compiled = re.compile(regex)
if compiled.method(query) is True:
print "We have some sort of match!"
else:
print "We do not have a match..."
当我尝试它时,我得到一个错误的错误:即使我将“ search”作为第三个参数(即使在编译时也可以调用),“ _ sre.SRE_pattern”却没有属性“ method”。我在做什么错或对这里的理解不完全?
method
作为字符串传递,并使用getattr:
def finder (regex, query, method):
compiled = re.compile(regex)
if getattr(compiled, method)(query):
print "We have some sort of match!"
else:
print "We do not have a match..."
finder(regex, query, "search")
另外,使用
if condition
代替
if condition is True
因为当compiled.method(query)
找到匹配项时,它会返回一个匹配对象,而不是True
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句