8

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+

Butterfly Coder
  • 197
  • 2
  • 11
  • [This](http://stackoverflow.com/questions/3849576/how-to-call-a-static-method-of-a-class-using-method-name-and-class-name) might be of some assistance! – Iggydv May 11 '17 at 07:15

3 Answers3

8

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()
Rahul K
  • 665
  • 10
  • 25
1

You can use importlib for this. Try importlib.import(module +"." + class +"."+ method)

Note that this concatenated string should look exactly like if you would import it via import module.class.method

Sebastian Walla
  • 1,104
  • 1
  • 9
  • 23
1

Try this:

# you get the module and you import
module = __import__(module_name)

# you get the class and you can use it to call methods you know for sure
# example class_obj.get_something()
class_obj = getattr(module, class_name)

# you get the method/filed of the class
# and you can invoke it with method() 
method = getattr(class_obj, method_name)
stefan.stt
  • 2,357
  • 5
  • 24
  • 47