zoukankan      html  css  js  c++  java
  • 装饰器

    装饰器:

    定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能

    原则:

    1.不能修改被装饰函数的源代码(新增功能)

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

    ---》对于被修饰的函数,它感知不到装饰器的存在

    import time
    def timmer(func):
        def warpper(*args,**kwargs):
            start_time=time.time()
            func()     ????????????
            stop_time=time.time()
            print('the func run time is %s' %(stop_time-start_time))
        return warpper
    
    @timmer
    def test1():
        time.sleep(3)
        print('in the test1')
    
    test1()

     实现装饰器的知识储备:

    1.函数即‘变量’   2.高阶函数   3.嵌套函数   高阶函数 +嵌套函数   --》装饰器

    函数即‘变量’

    def bar():
        print('in the bar')
    def foo():
        print('in the foo')
        bar() 
    foo()
    
    def foo():
        print('in the foo')
        bar()
    def bar():
        print('in the bar')
    foo()
    先声明,再调用时内存中已经存在 故二者结果相同
    -------------------------------
    # def foo():
    #     print('in the foo')
    #     bar()
    #foo()
    # def bar():
    #     print('in the bar')
    
    x

    高阶函数:

    1.把一个函数名当做实参传给另一个函数 

    2.返回值中包含函数名

    import time
    def bar():
         time.sleep(3)
         print('in the bar')
    
    def test1(func):
         start_time=time.time()
         func()    #run bar
         stop_time=time.time()
         print("the func run time is %s" %(stop_time-start_time))
    
     test1(bar)    --------》in the bar
                                     the func run time is %s
    #在不改变源代码下为其添加功能  但调用方式改变 不是装饰器
    
    
    import time
    def bar():
        time.sleep(3)
        print('in the bar')
    def test2(func):
         start_time=time.time()
         return   func()    #run bar   不走下面了
         stop_time=time.time()
         print("the func run time is %s" %(stop_time-start_time))
    bar=test2(bar) 
    bar()
    #run bar #不修改函数调用方式 但是没有加新功能

    嵌套函数    def 内def 才叫嵌套

    def foo():
        print('in the foo')
        def bar():  #局部变量  内部调用
            print('in the bar')
        bar()
    foo() ---》
    in the foo
    in the bar

    把高阶函数引入嵌套函数

    import time
    def deco(func):
        start_time=time.time()
        return func   #run test1()  以下不运行  引入嵌套函数
        stop_time = time.time()
        print("the func run time  is %s" %(stop_time-start_time))
     
    def timer():
        def deco():
           pass
    
    def test1():
        time.sleep(1)
        print('in the test1')
    
    
    def test2():
        time.sleep(1)
        print('in the test2')
    
    test1=deco(test1)
    test1()
    test2=deco(test2)
    test2()

    装饰器

    装饰器1

    import
    time def timer(func): #timer(test1) func=test1 把test1的内存地址传给func 返回的是deco的内存地址 def deco(): start_time=time.time() func() #里面正常做 不用return 了 run test1 stop_time = time.time() print("the func run time is %s" %(stop_time-start_time)) return deco def test1(): time.sleep(1) print('in the test1') test1=timer(test1) #run deco -->run test1 test1() #调用test1 执行deco
    装饰器2

    import
    time def timer(func): #timer(test1) func=test1 把test1的内存地址传给func 返回的是deco的内存地址 def deco(): start_time=time.time() func() #里面正常做 不用return 了 run test1 stop_time = time.time() print("the func run time is %s" %(stop_time-start_time)) return deco @timer #相当于 test1=timer(test1) #run deco -->run test1 def test1(): time.sleep(1) print('in the test1') @timer #想要运行那个就写在哪个头部 def test2(): time.sleep(1) print('in the test2') test1() #调用test1 执行deco test2()
    装饰器3  可以有无参数
    import
    time def timer(func): def deco(*args,**kwargs): start_time=time.time() func(*args,**kwargs) #run test2() stop_time = time.time() print("the func run time is %s" %(stop_time-start_time)) return deco @timer def test1(): time.sleep(1) print('in the test1') @timer # test2=timer(test2) =deco test2(name) =deco(name) def test2(name,age): print("test2:",name,age) test1() test2("alex",22)

    一层装饰器

    import time
    user,passwd = 'alex','abc123'
    def auth(auth_type):
          def wrapper(*args, **kwargs):
                    username = input("Username:").strip()
                    password = input("Password:").strip()
                    if user == username and passwd == password:
                        print("33[32;1mUser has passed authentication33[0m")
    func(*args, **kwargs) 
    else: exit("33[31;1mInvalid username or password33[0m") return wrapper def index(): print("welcome to index page") @auth def home(): print("welcome to home page") @auth def bbs(): print("welcome to bbs page") index() home() bbs()

    增加返回

    import time
    user,passwd = 'alex','abc123'
    def auth(auth_type):
          def wrapper(*args, **kwargs):
                    username = input("Username:").strip()
                    password = input("Password:").strip()
                    if user == username and passwd == password:
                        print("33[32;1mUser has passed authentication33[0m")
                        #run  home 没结果  可以res返回  
                         res = func(*args, **kwargs)  # from home
                        print("---after authenticaion ")
                        return res
                    else:
                        exit("33[31;1mInvalid username or password33[0m") 
            return wrapper
    
    def index():
        print("welcome to index page")
    
    @auth
    def home():
        print("welcome to home  page")
    return "from home" @auth
    def bbs(): print("welcome to bbs page") index() print(home()) #wrapper() bbs()
  • 相关阅读:
    标准差和方差
    Prism+WPF使用DependencyInjection实现AutoMapper的依赖注入功能
    集合框架3-Arrays 类
    集合框架2- ArrayList
    Windows 下安装 SSH 服务(Openssh)
    利用 Spring Boot 中的 @ConfigurationProperties,优雅绑定配置参数
    Spring系列.Environment接口
    (4)ElasticSearch在linux环境中搭建集群
    (1)RabbitMQ在Docker上安装
    说一说Web端侧AI
  • 原文地址:https://www.cnblogs.com/hmm1995/p/10146544.html
Copyright © 2011-2022 走看看