装饰器_下

示例1
from time import ctime,sleep
#导包就不需要使用包名.函数了
def timefun(func):

    def wrappedfunc():
        print("%s called at %s"%(func.__name__,ctime()))

        func()#内部函数需要使用外部函数的参数
    return wrappedfunc#返回内部函数

@timefun #timefun是一个闭包函数
def foo():#将foo函数传递给timefun闭包函数
    print("I'm foo ")

foo()
sleep(3)
foo()

'''
foo called at Fri May  8 01:00:18 2020
I'm foo 
foo called at Fri May  8 01:00:21 2020
I'm foo 
'''

示例2
from time import ctime,sleep
import functools

def timefun(func):
    #functools.wraps(func)
    def wrappedfunc(a,b):#使用了timefun函数的参数a,b

        print("%s called at %s"%(func.__name__,ctime()))
        print(a,b)
        func(a,b)

    return wrappedfunc

@timefun
def foo(a,b):
    print(a+b)

foo(3,5)
sleep(2)
foo(2,4)
'''
foo called at Fri May  8 01:01:16 2020
3 5
8
foo called at Fri May  8 01:01:18 2020
2 4
6
'''

示例3
from time import ctime,sleep

def timefun(func):

    def wrappedfunc(*args,**kwargs):
        # *args主要是元组,列表,单个值的集合
        # **kwargs 主要是键值对,字典
        print("%s called at %s"%(func.__name__,ctime()))
        func(*args,**kwargs)

    return wrappedfunc

@timefun
def foo(a,b,c):
    print(a+b+c)

foo(3,5,7)
sleep(2)
foo(2,4,9)
'''
foo called at Fri May  8 01:01:38 2020
15
foo called at Fri May  8 01:01:40 2020
15
'''

示例4
def timefun(func):

    def wrappedfunc( ):
        return func( )#闭包函数返回调用的函数(原函数有return)

    return wrappedfunc

@timefun
def getInfo():
    return '----haha----'

info = getInfo()#接收函数的返回值

print(info)#输出getInfo 如果闭包函数没有return 返回,则为None



'''
----haha----
'''

示例5
from time import ctime,sleep

def timefun_arg(pre = "Hello"):#使用了pre默认参数

    def timefun(func):
        def wrappedfunc():#闭包函数嵌套闭包函数
            print("%s called at %s"%(func.__name__,ctime()))
            print(pre)
            # func.__name__函数名 ctime()时间
            return func#返回使用了装饰器的函数
        return wrappedfunc
    return timefun

@timefun_arg("foo的pre")#对闭包函数中最外部函数进行形参传递pre
def foo( ):
    print("I'm foo")

@timefun_arg("too的pre")
def too():
    print("I'm too")

foo()
sleep(2)
foo()
too()
sleep(2)
too()

'''foo called at Fri May  8 01:02:34 2020
foo的pre
foo called at Fri May  8 01:02:36 2020
foo的pre
too called at Fri May  8 01:02:36 2020
too的pre
too called at Fri May  8 01:02:38 2020
too的pre
'''

2020-05-08

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12847002.html