Python通过函数名调用函数的几种场景

简介: Python通过函数名调用函数的几种场景

除了执行系统命令外,我们有时还需要动态地执行一些python代码,有经验的朋友就会知道可以使用内置函数eval实现这一需求,如eval("print(__file__)"),这还是比较简单的。

但如果要动态执行一个函数,讲的资料就会少一点,这次就要看这个需求该如何实现。

一、通过eval实现

1 通过eval调用同一个类内的函数

class TestA:
    def __init__(self):
        self.config_dict = {
   
            "be_called_function_name": "self.be_called_function()",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        be_called_function_name = self.config_dict["be_called_function_name"]
        # 就直接调用。如果有其他参数,一样地传就好了
        # 另外也可以是"be_called_function_name"是"be_called_function",然后eval(be_called_function_name)()
        eval(be_called_function_name)
        pass

    def be_called_function(self):
        print("here is be_called_function.")

if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

2 通过eval调用同一个文件内的一级函数

class TestA:
    def __init__(self):
        self.config_dict = {
   
            "be_called_function_name": "be_called_function()",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        be_called_function_name = self.config_dict["be_called_function_name"]
        # 就直接调用。如果有其他参数,一样地传就好了
        # 另外也可以是"be_called_function_name"是"be_called_function",然后eval(be_called_function_name)()
        eval(be_called_function_name)
        pass

def be_called_function():
    print("here is be_called_function.")

if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

二、通过getattr实现

1 通过函数名调用同一个类内的函数

class TestA:
    def __init__(self):
        self.config_dict = {
   
            "be_called_function_name": "be_called_function",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name传self即可
        be_called_function = getattr(self, self.config_dict["be_called_function_name"])
        # 就直接调用。如果有其他参数,一样地传就好了
        be_called_function()
        pass

    def be_called_function(self):
        print("here is be_called_function.")


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

2 通过函数名调用其他类的函数

class TestA:
    def __init__(self):
        self.config_dict = {
   
            "be_called_function_name": "be_called_function",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name传被调用的函数所在的类的类实例
        testb_obj = TestB()
        be_called_function = getattr(testb_obj, self.config_dict["be_called_function_name"])
        # 就直接调用。如果有其他参数,一样地传就好了
        be_called_function()
        pass


class TestB:
    def be_called_function(self):
        print("here is be_called_function.")


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

3 通过函数名调用同文件的一级函数

import sys


class TestA:
    def __init__(self):
        self.config_dict = {
   
            "be_called_function_name": "be_called_function",
        }
        pass

    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name传当前模块名
        module_name = sys.modules['__main__']
        be_called_function = getattr(module_name, self.config_dict["be_called_function_name"])
        # 就直接调用。如果有其他参数,一样地传就好了
        be_called_function()
        pass


def be_called_function():
    print("here is be_called_function.")


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()

4 通过函数名调用在其他文件的一级函数

class TestA:
    def __init__(self):
        self.config_dict = {
   
            "be_called_function_name": "be_called_function",
        }
        pass


    def active_call_function(self):
        print("here is active_call_function.")
        # getaattr(module_name, function_name),module_name传函数所在模块名
        # __import__()传函数所在文件
        module_name = __import__("test_call_function_by_string1")
        be_called_function = getattr(module_name, self.config_dict["be_called_function_name"])
        # 就直接调用。如果有其他参数,一样地传就好了
        be_called_function()
        pass


if __name__ == "__main__":
    obj = TestA()
    obj.active_call_function()
相关文章
|
2天前
|
Python
python之print函数
python之print函数
9 0
|
1天前
|
分布式计算 算法 Python
Python函数进阶:四大高阶函数、匿名函数、枚举、拉链与递归详解
Python函数进阶:四大高阶函数、匿名函数、枚举、拉链与递归详解
|
3天前
|
存储 Python
在Python中,匿名函数(lambda表达式)是一种简洁的创建小型、一次性使用的函数的方式。
【6月更文挑战第24天】Python的匿名函数,即lambda表达式,用于创建一次性的小型函数,常作为高阶函数如`map()`, `filter()`, `reduce()`的参数。lambda表达式以`lambda`开头,后跟参数列表,冒号分隔参数和单行表达式体。例如,`lambda x, y: x + y`定义了一个求和函数。在调用时,它们与普通函数相同。例如,`map(lambda x: x ** 2, [1, 2, 3, 4, 5])`会返回一个列表,其中包含原列表元素的平方。
13 4
|
3天前
|
Python
在Python中,高阶函数是指那些可以接受一个或多个函数作为参数,并返回一个新的函数的函数。
【6月更文挑战第24天】Python的高阶函数简化代码,增强可读性。示例:`map()`检查用户名合法性,如`["Alice", "Bob123", "Charlie!", "David7890"]`;`reduce()`与`lambda`结合计算阶乘,如1到10的阶乘为3628800;`filter()`找出1到100中能被3整除的数,如[3, 6, 9, ..., 99]。
12 3
|
4天前
|
SQL 分布式计算 大数据
MaxCompute产品使用问题之建了一个python 的 UDF脚本,生成函数引用总是说类不存在,是什么导致的
MaxCompute作为一款全面的大数据处理平台,广泛应用于各类大数据分析、数据挖掘、BI及机器学习场景。掌握其核心功能、熟练操作流程、遵循最佳实践,可以帮助用户高效、安全地管理和利用海量数据。以下是一个关于MaxCompute产品使用的合集,涵盖了其核心功能、应用场景、操作流程以及最佳实践等内容。
|
1天前
|
Python
经验大分享:python类函数,实例函数,静态函数
经验大分享:python类函数,实例函数,静态函数
|
1天前
|
Python
|
1天前
|
Python
经验大分享:Python函数返回值
经验大分享:Python函数返回值
|
2天前
|
Python
python函数
python函数
5 0
|
3天前
|
Python
使用Python计算有效值函数(RMS值)
使用Python计算有效值函数(RMS值)
9 0

热门文章

最新文章