Search code examples
pythonintrospection

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


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+


Solution

  • 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()