PHP前端开发

Python中如何在一个函数中加入多个装饰器

百变鹏仔 1个月前 (01-23) #Python
文章标签 多个
python中在一个函数中加入多个装饰器的方法:可以在函数名前使用@逐一添加装饰器,如【@decorator1 @decorator2】。装饰器与对象一样,可以赋值给一个变量,也可以在其它函数中定义。

Python中的函数就是对象,可以进行赋值、定义,多个装饰器的需要在函数名前使用@进行逐一添加,执行顺序是从上往下的,具体的操作过程需要在函数装饰器中进行。

首先我们知道函数就是对象,因此对象可以赋值给一个变量,也可以在其他函数里定义。

所以装饰器也是一样,这个例子中自定义了两个装饰器,然后在test()函数上添加了两个装饰器,运行结果正常。

#!/usr/bin/env python  #coding:utf-8  def decorator1(func):      def wrapper():          print 'hello python 之前'          func()      return wrapper    def decorator2(func):      def wrapper():          func()          print 'hello python 之后'      return wrapper   @decorator1  @decorator2  def test():      print 'hello python!'    test()

运行结果:

立即学习“Python免费学习笔记(深入)”;

hello python 之前hello python!hello python 之后