python 装饰器

来源:互联网 发布:中国cpi数据分析 编辑:程序博客网 时间:2024/06/01 19:36

Python装饰器

如果要增强某一函数的功能,但又不希望修改原函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。写代码需要遵循开放封闭原则,已经实现的功能代码不允许被修改,但可以被扩展

例如要给func函数增加一功能,只需定义一个login装饰器即可

deflogin(func):
    definner(arg,arg1):
        print('login')
        returnfunc(arg,arg1)
    returninner

@login       #此次相当于执行了func=login(func)
def func(arg,arg1):
    print('func: %s -- %s'%(arg,arg1))

func('hello','world')

运行结果:

login

func: hello -- world

 

如果decorator本身需要传入参数,那就需要编写一个返回decorator的高阶函数


def login(txt):
    defouter(func):
        definner(arg,arg1):
            print(txt)
            returnfunc(arg,arg1)
        returninner
    returnouter

@login('hehe') #装饰器带参数

#第一步执行login('hehe')

#第二步执行@outer(func)
def func(arg,arg1):
    print('func: %s -- %s'%(arg,arg1))

func('hello','world')

运行结果:

hehe

func: hello -- world

原创粉丝点击