首页 > 编程语言 >Python中通过反射来调用方法

Python中通过反射来调用方法

时间:2023-03-19 14:55:06浏览次数:34  
标签:function 反射 调用 name Python class callable my method

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

 

标签:function,反射,调用,name,Python,class,callable,my,method
From: https://www.cnblogs.com/chucklu/p/17233067.html

相关文章

  • Python如何将Markdown转成HTML,Python-Markdown2类库的使用
    Python-Markdown2是Python语言中一款轻量级的Markdown转换器,它可以将Markdown文本转换成HTML文档。在本教程中,我们将学习如何使用Python-Markdown2库。安装Python-Markdown2......
  • 111python之不定长参数
    Python中的不定长传参指的是函数参数的个数不是固定的,这使得函数可以接受任意数量的参数。有两种方法来实现不定长传参:使用*args和**kwargs参数。*args:用于传递任意数......
  • python语句之列表推导式
    python语句之列表推导式列表推导式是python语言特有的一种语法结构,也可以看成是python中独特的数据处理方法它在python中用转换和过滤数据语法格式:[表达......
  • python输入与输出
    python输入与输出python输出值的方式有两种:表达式语句print()函数str.format()函数用来格式化输出值,可以让输出的形式多样化;repr()和str()函数可以将输出值改为......
  • 功能强大,但因安全隐患被企业禁用的Python内置函数
    eval()函数是Python的内置函数,功能非常强大,但是存在不小的安全隐患。有些企业或项目出于安全考虑,禁止使用eval()函数,会在一些安全相关的扫描校验中进行识别和拦截,杜绝使用。究......
  • Python三次样条插值与MATLAB三次样条插值简单案例
    1三次样条插值早期工程师制图时,把富有弹性的细长木条(所谓样条)用压铁固定在样点上,在其他地方让它自由弯曲,然后沿木条画下曲线,成为样条曲线。设函数S(x)∈C2[a,b],且在每......
  • 使用LRU加速python应用
    操作系统:CentOS7.6.1810_x64Python版本:3.9.12一、背景描述使用python开发过程中,会遇到需要使用缓存加速应用的情况,比如下面这些场景:数据转换加速字符串时间......
  • Python中矩阵运算(基于numpy包)
    1乘法在数组中,a*a计算对应元素相乘(矩阵点乘);在矩阵中,A*A计算矩阵乘法np.multiply()计算对应元素相乘(矩阵点乘)np.dot()计算矩阵乘法importnumpyasnpa=np.array(......
  • python中矩阵切片维数微秒变化
    1前言使用切片访问矩阵的部分数据(特别是一行或一列数据)时,通常会出现切片维数怎么在瞎变化,以致于不得不用reshape()强制改变维数。在深度学习中,网络对矩阵维数的要求是非......
  • python重新命名,名字简短化
    #filedeal.py#!/usr/bin/envpython#-*-coding:utf-8-*-importosimportshutilfromPILimportImageimportioimportrequestsimportdatetime#获取所......