如何通过字符串方法名称调用类中的python静态方法[复制](How to invoke a python static method inside class via string method n

编程入门 行业动态 更新时间:2024-10-28 18:35:15
如何通过字符串方法名称调用类中的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 answers

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+

最满意答案

使用__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()

更多推荐

本文发布于:2023-07-05 02:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1032096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   字符串   静态   类中   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!