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

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

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

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

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

我如何在 python 2.7+

中实现这一点

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

请注意,如果您通过 import 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)

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

使用getattr(object, name) to access names from an object (module/class or anything)

在这里你可以做

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