How to launch getattr function in python with additional parameters?

前端 未结 3 1827
栀梦
栀梦 2021-01-31 09:08

I want to call some unknown function with adding parameters using getattr function. Is it possible?

相关标签:
3条回答
  • 2021-01-31 09:22

    Yes, but you don't pass them to getattr(); you call the function as normal once you have a reference to it.

    getattr(obj, 'func')('foo', 'bar', 42)
    
    0 讨论(0)
  • 2021-01-31 09:29

    If you wish to invoke a dynamic method with a dynamic list of arguments / keyword arguments, you can do the following:

    function_name = 'wibble'
    args = ['flip', 'do']
    kwargs = {'foo':'bar'}
    
    getattr(obj, function_name)(*args, **kwargs)
    
    0 讨论(0)
  • 2021-01-31 09:29
    import sys
    
    
    # function to call
    def wibble(a, b, foo='foo'):
        print(a, b, foo)
    
    
    # have to be in the same scope as wibble
    def call_function_by_name(function_name, args=[], kwargs={}):
        getattr(sys.modules[__name__], function_name)(*args, **kwargs)
    
        
    call_function_by_name('wibble', args=['arg1', 'arg2'], kwargs={'foo': 'bar'})
    # output:
    # arg1 arg2 bar
    
    0 讨论(0)
提交回复
热议问题