python 装饰器

装饰器 顾名思义 就是一个用来修改其他函数的功能的函数。

def new_decorator(a_func): #装饰器函数
 
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
 
        a_func()
 
        print("I am doing some boring work after executing a_func()")
 
    return wrapTheFunction
 
def function_requiring_decoration(): #被装饰的函数
    print("I am the function which needs some decoration to remove my foul smell")
 
function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
 
function_requiring_decoration = new_decorator(function_requiring_decoration) #通过装饰器函数得到新函数功能
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
 
function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

实际使用时 可以将 @装饰器函数 放在被装饰的函数前 来实现函数添加功能的方法。

@new_decorator
def function_requiring_decoration():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
 
function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()
 
#the @new_decorator is just a short way of saying:
function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

这样做修改之后会有一个问题: 函数名和注释文档会变成 装饰器中返回函数的名称与其对应的文档。

print(function_requiring_decoration.__name__)
# Output: wrapTheFunction

解决的方法:

使用functiontools 中的wraps函数

from functools import wraps
 
def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction
 
@a_new_decorator
def a_function_requiring_decoration():
    """Hey yo! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
 
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration

装饰器应用实例:

日志:

from functools import wraps
 
def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs): 
        print(func.__name__ + " was called")
        return func(*args, **kwargs) #需要返回被装饰的函数本身 
    return with_logging
 
@logit
def addition_func(x):
   """Do some math."""
   return x + x
 
 
result = addition_func(4)
# Output: addition_func was called
print(result)
# Output: 8

 

posted @ 2022-06-23 15:49  zed99  阅读(10)  评论(0编辑  收藏  举报