Python基础【装饰器】

装饰器:

装饰器:用来修改函数功能的函数

  • 可以在不改变原函数的基础上添加功能
    实现装饰器的方法:从函数中返回函数,将原函数作为一个参数传给另一个函数

    代码:装饰器pro_print在函数执行前输出提示"welcome to class"

    def pro_print(fun): # 装饰器函数
    def wrapper(*args,**kwargs): # 接收各种类型的不定长参数
    print("welcome to class")
    fun()
    return wrapper
    @pro_print # 语法糖,在函数前使用用于装饰函数
    def fun():
    print('hello,python')
    fun()

    但装饰器会覆盖原有函数的函数名,提示文档等信息

    def pro_print(fun): # 装饰器函数
    def wrapper(*args,**kwargs): # 接收各种类型的不定长参数
    '''执行函数前提示welcom to class'''
    print("welcome to class")
    fun()
    return wrapper
    @pro_print # 语法糖,在函数前使用用于装饰函数
    def fun():
    '''输出hello,python'''
    print('hello,python')
    fun()
    print(fun.__name__)
    print(fun.__doc__)

    测试结果:

    Python基础【装饰器】


导入functools中的wraps函数可以解决这个问题

from functools import wraps
def pro_print(fun): # 装饰器函数
@wraps(fun)
def wrapper(*args,**kwargs): # 接收各种类型的不定长参数
'''执行函数前提示welcom to class'''
print("welcome to class")
fun()
return wrapper
@pro_print # 语法糖,在函数前使用用于装饰函数
def fun():
'''输出hello,python'''
print('hello,python')
fun()
print(fun.__name__)

测试结果:

Python基础【装饰器】

猜你喜欢

转载自blog.51cto.com/13992211/2330382