Python编程举例-装饰器

  • 装饰器的通常用途是扩展已定义好的函数的功能

一个浅显的装饰器编程例子


#装饰器函数
def outer(fun):
    def wrapper():
        #添加新的功能
        print('验证')
        fun()
    return wrapper #必须返回整个函数

@outer
#被装饰的函数
def Func1():
    print('func1')
@outer
def Func2():
    print('func2')
@outer
def Func3():
    print('func3')

Func1()
Func2()
Func3()

装饰器函数接收参数和返回参数


#装饰器函数
def outer(fun):
    def wrapper(arg): #带上参数,参数是传递到wrapper函数
        #添加新的功能
        print('验证')
        result = fun(arg) #接收原函数的返回值
        return result #返回一个返回值
    return wrapper #必须返回整个函数

@outer #等同于outer(Func1)
#被装饰的函数
def Func1(arg): #带参数
    print('func1',arg)
    return 'return'
'''
Func1 =
def wrapper(arg):
    print('验证')
    result = fun(arg)
    return reuslt
'''
@outer
def Func2(arg):
    print('func2',arg)
@outer
def Func3(arg):
    print('func3',arg)

response = Func1('alex')
print(response)
Func2('lisa')
Func3('ted')


>>>>>>>>>
验证
func1 alex
return #返回值
验证
func2 lisa
验证
func3 ted
原文地址:https://www.cnblogs.com/konglinqingfeng/p/9662985.html