python 装饰器 part1

发布时间:2019-06-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了python 装饰器 part1脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

python 装饰器

早就应该掌握的技能。。。。

装饰器:本质是函数,用来装饰其他的函数,给他们附加功能。

实现装饰器要素

  1. 函数既‘变量’,以操作变量的形式操作函数;
  2. 高阶函数和嵌套函数的使用;

函数既‘变量’

代码举例

import time
def func(f):
    '''
    将函数以变量的形式传递进来
    '''
    start = time.time()
    f()
    end = time.time()
    PRint('函数f(也就是test)的运行时间是:{}'.format(end-start))
    print('in func....')
    return f
    
def test():
    time.sleep(2)
    print('in test.....')
    
val = func(test) # val == test
val() # test()
# 以上实现了一个特别native的装饰器功能,
# 在func内部可以增加其他功能(例如计算函数运行时间),最后return f

嵌套函数

进一步改进

import time
def decorator(func):
    def process():
        start = time.time()
        func()
        end = time.time()
        print('函数func(也就是被装饰的函数)的运行时间是:{}'.format(end-start))
    return process
    
def decorated():
    time.sleep()
    print('decorated function')
    
decorated = decorator(decorated) # decorated = return 来的process
decorated() # 也就是调用process

最终版

import time
def decorator(func):
    def process():
        start = time.time()
        func()
        end = time.time()
        print('函数func(也就是被装饰的函数)的运行时间是:{}'.format(end-start))
    return process

@decorator # python 装饰器的正确使用    
def decorated():
    time.sleep()
    print('decorated function')

# 此时不用再像上面一样赋值,可以直接调用
decorated()    

脚本宝典总结

以上是脚本宝典为你收集整理的python 装饰器 part1全部内容,希望文章能够帮你解决python 装饰器 part1所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。