Python calls the method with a string name

Sometimes, some special cases, the method name string to invoke methods need to use. Now make a note to avoid later been found.

How to use strings to call functions / methods?

There are many techniques to choose from.

The best practice is to use a mapping function to the dictionary string. The main advantage of this technique is that the string does not have to be consistent with the function name. This is the main technique used to simulate other structures in the case of language:

def a():
    pass

def b():
    pass

dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs

dispatch[get_input()]()  # Note trailing parens to call function

Use the built-in function getattr ()

import foo
getattr(foo, 'bar')()

Note getattr () can be used for any object, including classes, class instances, modules, and the like.

In the standard library I used this technique many times, for example:

class Foo:
    def do_foo(self):
        ...

    def do_bar(self):
        ...

f = getattr(foo_instance, 'do_' + opname)
f()

Using locals () or eval () function to resolve the name:

def myFunc():
    print("hello")

fname = "myFunc"
f = locals()[fname]
f()

f = eval(fname)
f()

Note: Using the eval () is slow and dangerous. If you absolutely can not control the contents of the string, others will be able to pass any string can be resolved to execute the function directly.

Guess you like

Origin www.linuxidc.com/Linux/2020-01/162141.htm