首页 > 编程技术 > python

python通过函数名调用函数的几种方法总结

发布时间:2021-6-7 00:00

一、通过eval实现

 常用内置函数

(不用import就可以直接使用) :

1.通过eval调用同一个类内的函数 eval()使用原因:

1)在编译语言里要动态地产生代码,基本上是不可能的,但动态语言是可以,意味着软件已经部署到服务器上了,但只要作很少的更改,只好直接修改这部分的代码,就可立即实现变化,不用整个软件重新加载。

2)在machin learning里根据用户使用这个软件频率,以及方式,可动态地修改代码,适应用户的变化。

eval()函数

eval(expression[, globals[, locals]])

返回传入字符串的表达式的结果

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实现

getattr() 函数用于返回一个对象属性值。语法如下:

getattr(object, name[, default])

getattr(object, name) = object.name
getattr(a, ‘b')的作用就和a.b是一样的

示例:

result = obj.method(args)
 
// 使用getattr
func = getattr(obj, "method")
result = func(args)
// 或者写成一行
result = getattr(obj, "method")(args)

主要有两种异常,异常的安全用法:
AttributeError:对象中没有该属性。

try:
    func = getattr(obj, "method")
except AttributeError:
    ...... deal
else:
    result = func(args)
 
// 或指定默认返回值
func = getattr(obj, "method", None)
if func:
    func(args)

TypeError: 不可调用

func = getattr(obj, "method", None)
if callable(func):
    func(args)

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()

到此这篇关于python通过函数名调用函数的几种方法总结的文章就介绍到这了,更多相关python通过函数名调用函数内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: