python补充学习.装饰器
Posted qq_51102350
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python补充学习.装饰器相关的知识,希望对你有一定的参考价值。
装饰器
一,定义和功能
把一个函数作为参数,返回一个替代版的函数
本质上是一个返回函数的参数
在不改变原函数的基础上,给函数增加新的功能
二,@修饰符
def a_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
@a_new_decorator
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
相当于:
def a_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 a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
a_function_requiring_decoration()
三,functools.wraps()函数
问题:
print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction
希望输出a_function_requiring_decoration,但输出了wrapTheFunction
可见a_function_requiring_decoration被wrapTheFunction替代了
此时用warps()函数来解决该问题
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 decorator_name(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
return "Function will not run"
return f(*args, **kwargs)
return decorated
@decorator_name
def func():
return("Function is running")
can_run = True
print(func())
# Output: Function is running
can_run = False
print(func())
# Output: Function will not run
以上是关于python补充学习.装饰器的主要内容,如果未能解决你的问题,请参考以下文章