当前位置 博文首页 > python通过函数名调用函数的几种方法总结

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

    作者:初学小白Lu 时间:2021-08-10 18:34

    一、通过eval实现

     常用内置函数

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

    • help(obj) 在线帮助, obj可是任何类型
    • callable(obj) 查看一个obj是不是可以像函数一样调用
    • repr(obj) 得到obj的表示字符串,可以利用这个字符串
    • eval重建该对象的一个拷贝
    • eval_r(str) 表示合法的python表达式,返回这个表达式
    • dir(obj) 查看obj的name space中可见的name
    • hasattr(obj,name) 查看一个obj的name space中是否有name
    • getattr(obj,name) 得到一个obj的name space中的一个name
    • setattr(obj,name,value) 为一个obj的name space中的一个name指向vale这个object
    • delattr(obj,name) 从obj的name space中删除一个name vars(obj) 返回一个object的name
    • space。用dictionary表示
    • locals() 返回一个局部name space,用dictionary表示
    • globals() 返回一个全局name space,用dictionary表示
    • type(obj) 查看一个obj的类型
    • isinstance(obj,cls) 查看obj是不是cls的instance
    • issubclass(subcls,supcls) 查看subcls是不是supcls的子类

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

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

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

    eval()函数

    eval(expression[, globals[, locals]])
    • 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])
    • object – 对象。
    • name – 字符串,对象属性。
    • default – 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

    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()
    
    jsjbwy
    下一篇:没有了