将方法作为函数参数传递

时间:2013-09-06 21:17:19

标签: python regex methods parameter-passing

是否可以将方法作为函数参数传递?

在学习正则表达式以及如何使用它们时,我决定尝试使用所使用的不同正则表达式方法重复调用一个函数:

    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..."

当我尝试它时,我得到一个属性错误:'_sre.SRE_pattern'没有属性'method',即使我将“search”作为第3个参数传递,它应该在编译时可调用。我在做什么不正确或者没有完全理解?

1 个答案:

答案 0 :(得分:3)

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