python装饰器

import time
def wrapper(type):
    print('start------',type)
    def outter(fun):
        def inner(*args,**kwargs):
            start_time = time.time()
            fun(*args,**kwargs)
            end_time=time.time()
            print('run time %d'%(end_time-start_time))
            return 'ret'
        print('------end')
        return inner
    return outter
@wrapper(type='3333')
def fun1(name,age):
    time.sleep(3)
    print('fun1 run',name,age)

#fun1=wrapper(fun1)
#fun1('howhy',34)#被装饰的函数带参数@wrapper()
#fun1=wrapper('aaa1')(fun1)#装饰器带参数@wrapper(type='3333')
ret=fun1('aaa4',34)#被装饰的函数返回值 
print(ret)
import time
def wrapper(fun):
    print('start wrapper fun')
    def inner():
        stime=time.time()
        fun()
        endtime=time.time()
        print('fun run time %d'%(endtime-stime))

    print('end wrapper fun')
    return inner

##被装饰的函数带参数
def wrapperFunArgs(fun):
    print('start wrapper fun')
    def inner(*args,**kwargs):
        stime=time.time()
        fun(*args,**kwargs)
        endtime=time.time()
        print('fun run time %d'%(endtime-stime))

    print('end wrapper fun')
    return inner

##装饰带参数
def wrapperFunArgs1(type):
    print('start wrapper fun',type)
    def outter(fun):
        def inner(*args,**kwargs):
            stime=time.time()
            fun(*args,**kwargs)
            endtime=time.time()
            print('fun run time %d'%(endtime-stime))
            return 'ret'  #被装饰的函数返回值
        print('end wrapper fun')
        return inner
    return outter
#@wrapper
@wrapperFunArgs1(type='333')
def fun(*args,**kwargs):
    time.sleep(3)
    print(' run fun',args,kwargs)

#fun=wrapper(fun) ##44 45行相当于在fun函数上加装饰器@wrapper
#fun()
#fun=wrapperFunArgs(fun) ##46 47行相当于在fun函数上加装饰器@wrapperFunArgs
#fun('howhy',23)
fun()
import functools
def funDecorator(fun):
    ##@functools.wraps(fun)##这样__name__就可以获取到被装饰函数的名、
    def inner(*args,**kwargs):
        ret=fun(*args,**kwargs)
        return ret
    return inner
@funDecorator
def fun1(name):
    print(name)

##若没有@functools.wraps(fun)则__name__为 inner 有则为fun1 
print(fun1.__name__) 

  

  

  

posted @ 2023-12-01 10:07  howhy  阅读(3)  评论(0编辑  收藏  举报