Use a string to call function in Python

This question already has an answer here:

  • Calling a function of a module by using its name (a string) 10 answers

  • You could use eval():

    myString = "fullName( name = 'Joe', family = 'Brand' )"
    result = eval(myString)
    

    Beware though, eval() is considered evil by many people.


    This does not exactly answer your question, but maybe it helps nevertheless:

    As mentioned, eval should be avoided if possible. A better way imo is to use dictionary unpacking. This is also very dynamic and less error prone.

    Example:

    def fullName(name = "noName", family = "noFamily"):
        return name + family
    
    functionList = {'fullName': fullName}
    
    function = 'fullName'
    parameters = {'name': 'Foo', 'family': 'Bar'}
    
    print functionList[function](**parameters)
    # prints FooBar
    
    parameters = {'name': 'Foo'}
    print functionList[function](**parameters)
    # prints FoonoFamily
    

    I know this question is rather old, but you could do something like this:

    argsdict = {'name': 'Joe', 'family': 'Brand'}
    globals()['fullName'](**argsdict)
    

    argsdict is a dictionary of argument, globals calls the function using a string, and ** expands the dictionary to a parameter list. Much cleaner than eval . The only trouble lies in splitting up the string. A (very messy) solution:

    example = 'fullName(name='Joe',family='Brand')'
    # Split at left parenthesis
    funcname, argsstr = example.split('(')
    # Split the parameters
    argsindex = argsstr.split(',')
    # Create an empty dictionary
    argsdict = dict()
    # Remove the closing parenthesis
    # Could probably be done better with re...
    argsindex[-1] = argsindex[-1].replace(')', '')
    for item in argsindex:
        # Separate the parameter name and value
        argname, argvalue = item.split('=')
        # Add it to the dictionary
        argsdict.update({argname: argvalue})
    # Call our function
    globals()[funcname](**argsdict)
    
    链接地址: http://www.djcxy.com/p/55160.html

    上一篇: 如何根据名称动态调用对象的函数?

    下一篇: 使用一个字符串在Python中调用函数