简体   繁体   中英

Pass a method as a function parameter

Is it possible to pass a method as a function parameter?

In learning regular expressions and how to use them, I decided to try and create a function I can just repeatedly call with the different regular expression methods that are used:

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

When I try it out, I get an atrribute error: '_sre.SRE_pattern' has no attribute 'method' even though I pass "search" as the 3rd parameter, which should be callable on compiled. What am I doing incorrectly or not completely understanding here?

Pass method as a string, and use 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")

Also, use

if condition

instead of

if condition is True

because when compiled.method(query) finds a match, it returns a match object, not True .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM