如何通过字符串方法名称调用类中的python静态方法[复制](How to invoke a python static method inside class via string method name [duplicate])
这个问题在这里已经有了答案:
通过使用其名称(字符串)调用模块的功能 10个答案我定义了以下字符串,它们指定了python模块名称,python类名称和静态方法名称。
module_name = "com.processors" class_name = "FileProcessor" method_name = "process"我想调用method_name变量指定的静态方法。
我如何在python 2.7+中实现这一点
This question already has an answer here:
Calling a function of a module by using its name (a string) 11 answersI 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+
最满意答案
使用__import__函数通过给出模块名称作为字符串来导入模块。
使用getattr(object, name)来访问对象(模块/类或其他 )的名称
在这里你可以做
module = __import__(module_name) cls = getattr(module, claas_name) method = getattr(cls, method_name) output = method()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()更多推荐
发布评论