How to launch getattr function in python with additional parameters?

给你一囗甜甜゛ 提交于 2019-12-31 08:44:32

问题


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


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/6321940/how-to-launch-getattr-function-in-python-with-additional-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!