3-13 装饰器


import time
def fun(bian):   ###装饰器
    def fun_1():  ##定义
        start_time = time.time()
        bian()
        stop_time = time.time()
        print('it is run %s'%(stop_time-start_time))
    return fun_1
@fun      ##调用装饰器  也等于 aa = aa(fun)
def aa():
    time.sleep(3)
    print('it is in aa')

aa()
View Code

 升级版   装饰器

#!/bin/python
# -*-coding:utf-8-*-
import time
def fun(abc):
    print('it is %s'%abc)
    def outer(bian):###装饰器
        def fun_1(*args,**kwargs):  ##定义自定义参数符合任何 函数的 功能调用
            rec = bian(*args,**kwargs)   ### 111
            if abc == 'local1':
                start_time = time.time()
                print('it is  local11111111111')
                stop_time = time.time()
                print('it is run %s'%(stop_time-start_time))
                print('****'.center(20,'-'))
            else:
                print('gao mao xian a....')
            return rec    ###111  只有这样 引用函数如有 return 的话也会显示
        return fun_1
    return outer
@fun(abc='local1')     ##调用装饰器  也等于 aa = aa(fun)
def aa(it):
    time.sleep(3)
    print('it is in aa%s'%it)
@fun(abc = 'local2')
def bb():
    time.sleep(1)
    print('hello ')
    return 'welcome'
aa('cc')  
bb()
print(bb()) ###111这样 'welcome'就会显示 如不 rec的话 返回是 None
原文地址:https://www.cnblogs.com/th-lyc/p/8557801.html