装饰器传参精髓理解

xiaoxiao2021-02-28  61

1.  创建一个空的列表版

func_list = list()  # 或[]def set_fun(func):    def call_fun(*args, **kwargs):        return func(*args, **kwargs)    # 在定义的列表中添加call_fun    func_list.append(call_fun)    return call_fun@set_fundef test():    print("test")@set_fundef test2():    print("test2")

运行结果:

2.  创建一个空的字典版

fun_dict = dict()def set_args(url):    def set_fun(func):        def call_fun(*args, **kwargs):

            return func(*args, **kwargs)

        # 把地址与对应的函数建立关系         fun_dict[url] = call_fun         return call_fun     return set_fun @set_args("/index.py") def test():     print("test1") @set_args("/center.py") def test2():

    print("test2")

运行结果:

3.  运用场景

主要用于服务器与框架之间的连接,在框架里对用户输入的地址进行传参

转载请注明原文地址: https://www.6miu.com/read-2628221.html

最新回复(0)