python - Appeler une fonction d'un module en utilisant son nom (une chaîne)

Mots clés : pythonobjectpython

meilleur 5 Réponses python - Appeler une fonction d'un module en utilisant son nom (une chaîne)

vote vote

93

import foo method_to_call = getattr(foo, 'bar') result = method_to_call() 
result = getattr(foo, 'bar')() 
vote vote

88

locals()["myfunction"]() 
globals()["myfunction"]() 
vote vote

74

module = __import__('foo') func = getattr(module, 'bar') func() 
vote vote

68

# Get class from globals and create an instance m = globals()['our_class']()  # Get the function (from the instance) that we need to call func = getattr(m, 'function_name')  # Call it func() 
class A:     def __init__(self):         pass      def sampleFunc(self, arg):         print('you called sampleFunc({})'.format(arg))  m = globals()['A']() func = getattr(m, 'sampleFunc') func('sample arg')  # Sample, all on one line getattr(globals()['A'](), 'sampleFunc')('sample arg') 
def sampleFunc(arg):     print('you called sampleFunc({})'.format(arg))  globals()['sampleFunc']('sample arg') 
vote vote

51

import importlib function_string = 'mypackage.mymodule.myfunc' mod_name, func_name = function_string.rsplit('.',1) mod = importlib.import_module(mod_name) func = getattr(mod, func_name) result = func() 

Questions similaires