Python中通过反射来调用方法

Is there a way to pass invoke function by method name in string, which means call the method by reflection

Yes, you can use reflection in Python to invoke a method by passing its name as a string. The built-in getattr() function can be used to retrieve an attribute (such as a method) from an object by name, and the callable() function can be used to check if the attribute is callable (i.e. a method). Here's an example:

class MyClass:
    def my_method(self, arg):
        print("My method was called with argument:", arg)

# create an instance of MyClass
obj = MyClass()

# invoke the method by passing its name as a string
method_name = "my_method"
if hasattr(obj, method_name) and callable(getattr(obj, method_name)):
    method = getattr(obj, method_name)
    method("hello")

In this example, we define a class MyClass with a method my_method(). We create an instance of the class and then use reflection to retrieve the method object by name ("my_method") using getattr(). We then check that the attribute is callable using callable(), and if so we invoke the method with an argument ("hello"). The output of this code will be:

My method was called with argument: hello

 

What if I don't have a class name? Is there a default class name in python file only have methods in it? Is it possible to use method = getattr(obj, method_name)

If you don't have a class name and just want to call a function by name using reflection, you can use the built-in globals() function to get a dictionary of all the global variables in the current scope. This dictionary will contain any functions defined at the top level of the module. Here's an example:

def my_function(arg):
    print("My function was called with argument:", arg)

# invoke the function by passing its name as a string
function_name = "my_function"
if function_name in globals() and callable(globals()[function_name]):
    function = globals()[function_name]
    function("hello")

In this example, we define a function my_function(). We then use reflection to retrieve the function object by name ("my_function") using globals(), which returns a dictionary of all the global variables in the current scope. We then check that the attribute is callable using callable(), and if so we invoke the function with an argument ("hello"). The output of this code will be:

My function was called with argument: hello

Regarding your second question, if you only have methods defined in a module and no class, you can define a class with a default name (e.g. "MyClass") and add the methods as instance methods. Then you can use reflection to retrieve the method object by name using getattr() as usual. Here's an example:

def my_method(arg):
    print("My method was called with argument:", arg)

# define a class with a default name and add the method as an instance method
class MyClass:
    my_method = my_method

# create an instance of the class
obj = MyClass()

# invoke the method by passing its name as a string
method_name = "my_method"
if hasattr(obj, method_name) and callable(getattr(obj, method_name)):
    method = getattr(obj, method_name)
    method("hello")

In this example, we define a method my_method(). We then define a class MyClass with a default name and add the method as an instance method. We create an instance of the class and then use reflection to retrieve the method object by name ("my_method") using getattr(). We then check that the attribute is callable using callable(), and if so we invoke the method with an argument ("hello"). The output of this code will be:

My method was called with argument: hello

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(128)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-03-19 炉石传说 关键词
2022-03-19 毛概
2022-03-19 What is Big Data?
2022-03-19 Chapter 1: What Is an Information System?
2020-03-19 How much business logic should be allowed to exist in the controller layer?
2019-03-19 Kibana --> Getting Started -->Building your own dashboard
2019-03-19 Download and Installation of Kibana
点击右上角即可分享
微信分享提示