• 20-python-装饰器⭐


    1、什么式装饰器

      装饰器本质就是函数,为其他函数添加附加功能

      需要把握的原则:

      1、不修改被修饰函数的源代码

      2、不修改被装饰函数的调用方式

      装饰器的知识储备:

      装饰器=高阶函数+函数嵌套+闭包

      高阶函数的应用举例

     1 # -*- coding:utf-8 -*-
     2 import time
     3 def foo():
     4     time.sleep(1)
     5     print("from-foo:您好")
     6 def timmer(func):
     7     start_time=time.time()
     8     func()
     9     stop_time = time.time()
    10     print("from-time:运行时间%s"%(stop_time-start_time))
    11     return func
    12 
    13 foo=timmer(foo)
    14 foo()

      函数的嵌套举例

      函数里面在定义函数才是嵌套

     1 def father(name):
     2     print("from father %s" % name)
     3 
     4     def son():
     5         print("from son %s" % name)
     6 
     7         def grandson():
     8             name = "zf1"
     9             print("grandfather %s" % name)
    10 
    11     print(locals())
    12 
    13 
    14 father("zf")

       装饰器的构架

     1 # -*- coding:utf-8 -*-
     2 
     3 import time
     4 
     5 
     6 def timmer(func):
     7     def wrapper():
     8         start_time = time.time()
     9         func()
    10         stop_time = time.time()
    11         print("函数运行时间为%.4f" % (stop_time - start_time))
    12 
    13     return wrapper
    14 
    15 
    16 def test():
    17     print("函数正在运算中")
    18     time.sleep(3)
    19     print("函数运算完毕")
    20 
    21 
    22 test = timmer(test)   #   @timmer
    23 test()

    在@timmer====程序中第22行

     若test函数有返回值

     1 # -*- coding:utf-8 -*-
     2 
     3 import time
     4 
     5 
     6 def timmer(func):
     7     def wrapper():
     8         start_time = time.time()
     9         res = func()
    10         stop_time = time.time()
    11         print("函数运行时间为%.4f" % (stop_time - start_time))
    12         return res
    13 
    14     return wrapper
    15 
    16 
    17 @timmer
    18 def test():
    19     print("函数正在运算中")
    20     time.sleep(3)
    21     print("函数运算完毕")
    22     return "这是test的返回值"
    23 
    24 
    25 res = test()
    26 print(res)

    若test函数有参数

    # -*- coding:utf-8 -*-
    
    import time
    
    
    def timmer(func):
        def wrapper(*args,**kwargs):
            start_time = time.time()
            res = func(*args,**kwargs)
            stop_time = time.time()
            print("函数运行时间为%.4f" % (stop_time - start_time))
            return res
    
        return wrapper
    
    
    @timmer
    def test(name,age):
        print("函数正在运算中")
        time.sleep(1)
        print("函数运算完毕名字%s,年龄%s"%(name,age))
        return "这是test的返回值"
    
    
    res = test("zf",18)
    print(res)

    闭包函数加上认证功能举例

     1 # -*- coding:utf-8 -*-
     2 
     3 def test(func):
     4     def wrapper():
     5         name=input("name>>>")
     6         password=input("password>>>")
     7         if name=="zf" and password=="123456":
     8             func()
     9         else:
    10             print("登陆失败")
    11     return wrapper
    12 
    13 
    14 def home():
    15     print("登陆的自己的主页")
    16 
    17 @test
    18 def shopping_car():
    19     print("登陆到自己的购物车")
    20 
    21 # home()
    22 shopping_car()

    闭包函数模拟session

     1 # -*- coding:utf-8 -*-
     2 user_list=[{"username":"zf","passwd":"123456"},{"username":"zf1","passwd":"1234561"}]
     3 
     4 
     5 user_stat={"username":None,"login":False}
     6 
     7 
     8 
     9 def test(func):
    10     def wrapper():
    11         # global passkey
    12         if user_stat["username"]==None and user_stat["login"]==False:
    13             name = input("name>>>").strip()
    14             password = input("password>>>").strip()
    15             for user_dict in user_list:
    16                 if name == user_dict["username"] and password == user_dict["passwd"]:
    17                     user_stat["username"]=user_dict["username"]
    18                     user_stat["login"]=True
    19                     return func()
    20                     # break
    21             else:
    22                 print("登陆失败")
    23         else:
    24             return func()
    25 
    26     return wrapper
    27 
    28 
    29 @test
    30 def home():
    31     print("登陆的自己的主页")
    32 
    33 
    34 @test
    35 def shopping_car():
    36     print("登陆到自己的购物车")
    37     return "购物成功"
    38 
    39 
    40 home()
    41 res=shopping_car()
    42 print(res)

     闭包函数带参数的装饰器

     1 # -*- coding:utf-8 -*-
     2 user_list=[{"username":"zf","passwd":"123456"},{"username":"zf1","passwd":"1234561"}]
     3 
     4 
     5 user_stat={"username":None,"login":False}
     6 
     7 
     8 def test1(test_ytpe="file"):
     9     def test(func):
    10         def wrapper():
    11             print(test_ytpe)
    12             # global passkey
    13             if user_stat["username"]==None and user_stat["login"]==False:
    14                 name = input("name>>>").strip()
    15                 password = input("password>>>").strip()
    16                 for user_dict in user_list:
    17                     if name == user_dict["username"] and password == user_dict["passwd"]:
    18                         user_stat["username"]=user_dict["username"]
    19                         user_stat["login"]=True
    20                         return func()
    21                         # break
    22                 else:
    23                     print("登陆失败")
    24             else:
    25                 return func()
    26 
    27         return wrapper
    28     return test
    29 
    30 
    31 @test1()  #test=test1()   -->   @test  home=test(home)
    32 def home():
    33     print("登陆的自己的主页")
    34 
    35 
    36 @test1()
    37 def shopping_car():
    38     print("登陆到自己的购物车")
    39     return "购物成功"
    40 
    41 
    42 home()
    43 res=shopping_car()
    44 print(res)
  • 相关阅读:
    SQL关键字的执行顺序
    StructuredStreaming基础操作和窗口操作
    StructuredStreaming简单的例子(NewAPI)
    StructuredStreaming(New)
    StructuredStreaming编程模型
    SparkStreaming简单例子(oldAPI)
    SparkStreaming架构
    Storm与SparkStreaming对比
    SparkStreaming-DStream(Discretized Stream)
    史上最全的java随机数生成算法分享(转)
  • 原文地址:https://www.cnblogs.com/zhfang/p/8934602.html
Copyright © 2020-2023  润新知