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

    装饰器前奏:

    装饰器变形:

    (1)第一种变形

    (2)第二种变形

    (3)第三种变形

    (4)第四种变形(正确且标准得装饰器)

    装饰器装饰带有参数的函数:

     

    带标志位的装饰器:

     

    应用场景:例如装饰器是为了测试代码运行时间,但是生产环境上线是需要去掉多余得功能,这时候可以把装饰器标志位改为False即可,避免了频繁的删除操作。

    带参数的装饰器:

    import time
    
    current_login = {'name': None, 'login': False}
    
    def timmer(func):
        def wrapper(*args, **kwargs):
            start_time = time.time()
            res = func(*args, **kwargs)  # my_max(1,2)
            stop_time = time.time()
            print('run time is %s' % (stop_time - start_time))
            return res
        return wrapper
    
    def auth2(auth_type='file'):
        def auth(func):
            # print(auth_type)
            def wrapper(*args, **kwargs):
                if current_login['name'] and current_login['login']:
                    res = func(*args, **kwargs)
                    return res
                if auth_type == 'file':
                    name = input('username: ')
                    password = input('password: ')
                    if name == 'luchuan' and password == '123':
                        print('auth successfull')
                        res = func(*args, **kwargs)
                        current_login['name'] = name
                        current_login['login'] = True
                        return res
                    else:
                        print('auth error')
                elif auth_type == 'sql':
                    print('还他妈不会玩')
            return wrapper
        return auth
    
    @timmer
    @auth2(auth_type='file')  # @auth  #index=auth(index)
    def index():
        print('welcome to inex page')
    
    @auth2()
    def home():
        print('welcome to home page')
    
    # 调用阶段
    index()
    home()
  • 相关阅读:
    FILTER(过滤器)
    HDFS优缺点
    python运算符
    python变量类型
    python变量存储
    python编码问题
    【一:定义】python 简介
    如何学一门新技术
    Django安装
    redis 安装及启动关闭
  • 原文地址:https://www.cnblogs.com/bingabcd/p/6851024.html
Copyright © 2011-2022 走看看