• python 装饰器


    实现装饰器知识储备
    1、函数既“变量”
    2、高阶函数
    a:把一个函数名当做实参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

    b:返回值包含函数名(不能修改函数的调用方式)
    3、嵌套函数

    高阶函数+嵌套函数 =》 装饰器

    例子:

    # -*- coding:utf-8 -*-
    # Author:Jason

    import time

    def timer(func): #普通装饰器
    def deco(*args,**kwargs):
    start_time = time.time()
    func(*args,**kwargs)
    stop_time = time.time()
    print("the func run time is %s" %(stop_time-start_time))
    return deco

    @timer # @timer 等同于简写 test1 = timer(test1)
    def test1():
    time.sleep(1)
    print('this is test1')

    @timer
    def test2(name):
    print('test2:%s'%(name))

    test1()
    test2('jason')


    例子2:

    # -*- coding:utf-8 -*-
    # Author:Jason

    import time

    def auth(auth_type): #第一层可以获取判断你参数
    def outer_wrapper(fun): #普通装饰器
    def doce(*args,**kwargs):
    print('%s'%(auth_type))
    fun(*args,**kwargs)

    return doce
    return outer_wrapper


    @auth('local')
    def test1():
    print('this is a test1')

    @auth('www')
    def test2(one1,two1):
    print('this is a %s and %s'%(one1,two1))


    test1()
    test2(23,'ll')

  • 相关阅读:
    0705-深度网络模型持久化
    0704-使用GPU加速_cuda
    0703-可视化工具tensorboard和visdom
    0702-计算机视觉工具包torchvision
    00-凸优化引言
    MySQL数据库从入门到放弃(目录)
    0701-数据处理
    BurpSuite抓取HTTPS请求&&拦截Android请求
    数学里的e到底指什么
    QGeoPolygon
  • 原文地址:https://www.cnblogs.com/jasonLiu2018/p/10733395.html
Copyright © 2020-2023  润新知