Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a python static method inside class via string method name [duplicate]

I have a the following strings defined which are specifying a python module name, a python class name and a static method name.

module_name = "com.processors"
class_name = "FileProcessor"
method_name = "process"

I would like to invoke the static method specified by method_name variable.

How do i achieve this in python 2.7+

like image 693
Butterfly Coder Avatar asked May 11 '17 07:05

Butterfly Coder


1 Answers

Use __import__ function to import module by giving module name as string.

Use getattr(object, name) to access names from an object (module/class or anything)

Here u can do

module = __import__(module_name)
cls = getattr(module, claas_name)
method = getattr(cls, method_name)
output = method()
like image 101
Rahul K Avatar answered Sep 21 '22 12:09

Rahul K