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+

1
  • This might be of some assistance! Commented May 11, 2017 at 7:15

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.