Python装饰器基础语法总结

1 def require_login(func):                    # 传入func这个参数,是需要被装饰的函数
2     def proxy_func(self,*args,**kw):        # 这个函数对象,就是原始的函数:some_func被装饰后返回的函数对象。当然是在它被调用时才会执行。
3         print _web.input()                 # 做一些操作
4         return func(self,*args,**kw)       # 返回原始的函数,并加上参数
5     return proxy_func                       # 返回内层的函数对象

而真实的顺序是这样的:

1 1> def require_login(func):
2 3>    def proxy_func(self,*args,**kw):
3 4>        print _web.input()
4 5>        return func(self,*args,**kw)
5 2>    return proxy_func
1 @require_login
2 def some_func():
3     pass


上面的意思与下面的样子一样:

1 some_func_decoratored = require_login(some_func)


当执行some_func_decoratored()的时候,就相当于执行了上面的内层的函数。

整个过程大致如下:
1. 外层的require_login函数将some_func函数作为参数传入
2. 内层的proxy_func在执行时会将它捕捉到的环境参数带入,这里包括了外层函数require_login传入的func参数
3. 执行完了require_login(some_func)之后,会返回一个函数对象:proxy_func
4. proxy_func其实就是被装饰完成的函数对象,在调用some_func_decoratored()时,proxy_func执行!


而带有参数的装饰器,如下:

1 @eventhandler('BUTTON')
2 def some_func(args):
3     pass


执行语义如下:

1 def some_func(args):
2     pass
3 temp = eventhandler('BUTTON')    # 使用提供的参数调用装饰器
4 some_func = temp(some_func)        # 调用装饰器返回的函数



原文地址:https://www.cnblogs.com/huazi/p/2489883.html