Dynamic method invocation in python
In this article will see how to invoke a method with arguments
Code :
#sample class
class demo:
#method need to be invoked dynamically
def mymethod(self,myarg):
print(myarg)
#method to invoke a method in object
def invoke_method(method_name,args,obj):
kwargs =args
#get the method from the instance
method=getattr(obj,method_name)
return method(**kwargs)
#argument & value object
arg ={"myarg" : "hello world"}
invoke_method('mymethod',arg,demo())
How it works
- Created a sample class demo with a method mymethod
- new method invoke_method takes three method name , arguments (name value pairs),instance of the object
- Method object is fetched for the instance using getattr() function
- Method was invoked with keyworded arguments (**kwargs) - more on kwargs
Labels: method invocation, python

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home