Python常用各種類型的裝飾器模板

不帶參數:

def deco(func):
    def wrapper(*args,**kwargs):
        print("before wrapper")
        func(*args,**kwargs)
        print("after wrapper")
    return wrapper

@deco
def test():
    print("in test")
    
test()

帶參數:

def deco(*args,**kwargs):
    def wrapper(func):
        def inner(*args,**kwargs):
            print(args,kwargs)
            print("before wrapper")
            func(*args,**kwargs)
            print("after wrapper")
        return inner
    return wrapper

@deco()
def test():
    print("in test")

test()

類中不帶參數:

from functools import wraps
def wrapper(func):
    @wraps(func)
    def inner(self,*args,**kwargs):
        print("before wrapper")
        func(self,*args,**kwargs)
        print("after wrapper")
    return inner

class Test:

    @wrapper
    def test(self,*args,**kwargs):
        print("in class test",args,kwargs)

Test().test()

類中帶參數:

from functools import wraps
def deco(*wargs,**wkwargs):
    def wrapper(func):
        @wraps(func)
        def inner(self,*args,**kwargs):
            print("wrapper args:",wargs,wkwargs)
            print("before wrapper")
            func(self,*args,**kwargs)
            print("after wrapper")
        return inner
    return wrapper

class Test:

    @deco()
    def test(self,*args,**kwargs):
        print("in class test",args,kwargs)

Test().test()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章