首页 > 编程语言 >Python通过函数名调用函数的几种场景

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

时间:2024-04-13 16:34:40浏览次数:28  
标签:function __ 场景 name Python self 调用函数 call called

除了执行系统命令外,我们有时还需要动态地执行一些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()

标签:function,__,场景,name,Python,self,调用函数,call,called
From: https://www.cnblogs.com/djdjdj123/p/18133024

相关文章

  • Python教程:return和yield的区别
    return一直中,每中语言中其没没有很大差别,就不多说了。(shell语言return的是退出状态,可能差别是比较大的)最早看到yield应该是哪们语言用来调整什么线程优先级的,记不清了,不过那里的yield和python中的yield应该功能有区别。一、return和yield的异同共同点:return和yield都用来返回值......
  • Python中paramiko 模块的用法
    paramiko是一个用Python语言编写的、遵循SSH2协议、支持以加密和认证方式进行连接远程服务器的模块。改模块可以对远程服务器进行一些命令或文件操作。1.安装使用pip3安装paramiko模块pip3installparamiko连接远程服务器paramiko模块连接远程服务器可以使用远程......
  • centos6.5安装python3.6.9
    下载python:https://www.python.org/ftp/python/3.6.9/Python-3.6.9.tgz安装tar-zxvfPython-3.6.9.tgzcdPython-3.6.9./configure--prefix=/opt/python3.6makemakeinstallecho"/opt/python3.6/lib">/etc/ld.so.conf.d/python3.6.9.confsudoldconf......
  • Visual Studio Code & Python教程3顶级扩展
    3简介扩展功能非常宝贵。它们有助于提高代码质量,加快开发工作。我们将介绍一些必备的通用扩展。3.1顶级扩展3.1.1Pylance微软的Pylance可以大大提高你的工作效率。Pylance是一款Python语言服务器,它增强了IntelliSense、语法高亮和大量其他功能,为Python开发人员带来了令人......
  • python调用库生成自然语言语音包
    当前还没release版本,只能git安装pipinstallgit+https://github.com/huggingface/parler-tts.git代码fromparler_ttsimportParlerTTSForConditionalGenerationfromtransformersimportAutoTokenizerimportsoundfileassfimporttorchdevice="cuda:0"iftor......
  • React状态与引用(Refs)- 差异和使用场景
    在本文中,我们将深入比较React的state和refs,探讨它们在特定场景下的适用性。当需要在React应用程序中存储数据时,首先要考虑的问题是:“数据是否在组件的生命周期内的某个时刻发生变化?”如果不会,那么普通的const变量非常适合。然而,如果数据会发生变化,那么就需要使用useState和useR......
  • Go语言的100个错误使用场景(61-68)|并发实践
    目录前言9.并发实践9.1context的不恰当传播(#61)9.2开启一个协程但不知道何时关闭(#62)9.3在循环中没有谨慎使用协程(#63)9.4使用select和channel期待某个确定的行为(#64)9.5不使用用于通知的channel(#65)9.6不使用nilchannel(#66)9.7对channel的大小感到疑惑(#67)9.8忽视st......
  • 2-76. 跨场景地图的路径数据及生成
    修改DataCollection创建SceneRouteDataList_SO修改NPCManager修改Settings我们在场景里使用了99999,所以在Settings里面只能使用9999修改NPCManager绘制NPCObstacle修改TimeManager我们主角切换场景会有3秒淡入淡出的效果,我们希望在这三秒里NPC不要......
  • Python函数
    函数定义和调用defadd(x,y):#先定义ans=x+yreturnans#返回ansadd(4,5)#后调用注:定义函数时的“x和y”为形式参数,调用函数时的“4和5”为实际参数,当调用函数时,将实际参数“4和5”传递给形式参数“x和y”。None类型defsay_hello():#定义......
  • Python3 YOLOv8 体验
    参考https://docs.ultralytics.com/zh/quickstart/#use-ultralytics-with-pythonhttps://pytorch.org/get-started/locally/https://www.zhihu.com/question/275575243https://github.com/onnx/onnx/issues/5773https://stackoverflow.com/questions/72352528/how-to-fix-......