装饰器整理

装饰器

装饰器的定义:装饰器函数必须接受一个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相当于接受内部函数的变量

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