裝飾器整理

裝飾器

裝飾器的定義:裝飾器函數必須接受一個callable對象(一般是核心函數)作爲參數,然後返回一個callable對象(一般是裝飾器函數的功能函數)

裝飾器的作用:遵循封閉開放的原則,封閉指的是已經實現的功能代碼塊不允許被修改,開放指的是允許對外進行功能的擴展

1. 引⼊⽇志
2. 函數執⾏時間統計
3. 執⾏函數前預備處理
4. 執⾏函數後清理功能
5. 權限校驗等場景
6. 緩存

裝飾器的使用:

裝飾器的進階:
  """

# 被裝飾的函數無參數

from time import ctime, sleep
def timefun(func):
    def wrappedfunc():
        print("%s called at %s" % (func.__name__,ctime())) # 裝飾器的代碼
        func()   # 被裝飾的核心代碼
    return wrappedfunc
@timefun
def foo():
    print("i am foo")

foo()
sleep(2)
foo()
foo = timefun(foo)
"""


# 被裝飾的函數有參數

"""

from time import ctime,sleep

def timefun(func):
    def wrappedfunc(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)

"""
"""

#被裝飾的函數是不定長參數

from time import ctime,sleep

def timefun(func):
    def wrappedfunc(*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)

foo(2,5,9)
"""
"""

# 主函數是return的情況

from time import ctime,sleep

def timefun(func):
    def wrappedfunc():  
        print("%s called at %s" %(func.__name__,ctime()))
        return func()  
    return wrappedfunc
@timefun
def getinfo():
    return 'sdas'
getinfo()
print(getinfo())
"""

# 裝飾器嵌套,在裝飾器的外部嵌套一層外部變量

from time import ctime,sleep

def timefun_arg(pre = 'hello'):
    def timefun(func):
        def wrappedfunc():  
            print("%s called at %s %s" %(func.__name__,ctime(),pre))
            return func()  
        return wrappedfunc
    return timefun

@timefun_arg("itcast")
def foo():
    print("i am foo")
@timefun_arg("python")
def too():
    print("i am too")
foo()
too()
"""
功能需求:
在日記裏面記錄每次輸出f1的時間
主函數是f1
裝飾函數是日誌
"""

# 裝飾器函數

import time
def timer(f1):   # 裝飾器的外部函數要把主函數當參數傳入
    def wrapper(*args,**kwargs):  # 參數的傳遞
        with open(r'a.txt','a',encoding = 'utf-8') as f: # 文件操作
            f1()
            res = '%s %s run\n' % (time.strftime('%Y-%m-%d %X'),f1.__name__) #以格式寫入
            f.write(res)     # 寫入文件
    return wrapper



@timer   # 裝飾器的作用相當於調用

#主函數

def f1():
    print("函數f1執行")


f1()      #必須用主函數去調用內部函數,f1相當於接受內部函數的變量

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