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

举报
python教程 发表于 2024/06/21 15:29:30 2024/06/21
【摘要】 除了执行系统命令外,我们有时还需要动态地执行一些python代码,有经验的朋友就会知道可以使用内置函数eval实现这一需求,如eval("print(__file__)"),这还是比较简单的。但如果要动态执行一个函数,讲的资料就会少一点,这次就要看这个需求该如何实现。 一、通过eval实现1 通过eval调用同一个类内的函数class TestA: def __init__(self)...

除了执行系统命令外,我们有时还需要动态地执行一些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
        
	#学习中遇到问题没人解答?小编创建了一个Python学习交流群:153708845
    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()
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。