如何在类内通过字符串方法名称调用python静态方法

问题描述:

我有一个定义了下列字符串,它们指定了一个python模块名称,一个python类名称和一个静态方法名称。如何在类内通过字符串方法名称调用python静态方法

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

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

我如何在Python实现这一2.7+

+0

[这](http://stackoverflow.com/questions/3849576/how -to-call-a-static-method-a-class-using-method-name-and-class-name)可能会有一些帮助! – Iggydv

使用__import__功能通过给导入模块模块名称作为字符串。

使用getattr(object, name)从对象(模块/类或anything

这里访问名称u能做到

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

您可以使用导入库这一点。 尝试importlib.import(module +"." + class +"."+ method)

请注意,此连接字符串应该完全一样,如果你将通过进口module.class.method

导入试试这个:

# 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)