如何通过字符串方法名

时间:2017-05-11 07:04:20

标签: python introspection

我定义了以下字符串,它们指定了python模块名称,python类名称和静态方法名称。

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

我想调用method_name变量指定的静态方法。

我如何在python 2.7 +

中实现这一目标

3 个答案:

答案 0 :(得分:5)

使用__import__函数通过将模块名称作为字符串来导入模块。

使用getattr(object, name)访问对象中的名称(模块/类或anything

在这里你可以做到

module = __import__(module_name)
cls = getattr(module, claas_name)
method = getattr(cls, method_name)
output = method()

答案 1 :(得分:1)

您可以使用importlib。 试试importlib.import(module +"." + class +"."+ method)

请注意,如果您通过import module.class.method

导入它,那么这个连接的字符串应该看起来很像

答案 2 :(得分:1)

试试这个:

# 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)
相关问题