Python : decorator

decorator syntax

A function returning another function, usually applied as a function transformation using the @wrapper syntax.
A decorator is a callable that modifies functions, methods or classes.

@f1(arg)
@f2
def func(): 
    pass

is roughly equliant to

def func(): 
    pass
func = f1(arg)(f2(func))
  • Decorators as classes
class IdentityDecorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self):
        self.func()


@IdentityDecorator
def a_function():
    print "I'm a normal function."

a_function()
# >> I'm a normal function
  • !Note
    Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object.

Closure

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope(non-local variable).

>>> def make_printer(msg1, msg2):
      def printer():
          print msg1, msg2
      return printer
>>> printer = make_printer('Foo', 'Bar')  # 形成闭包

>>> printer.__closure__   # 返回cell元组
(<cell at 0x03A10930: str object at 0x039DA218>, <cell at 0x03A10910: str object at 0x039DA488>)

>>> printer.__closure__[0].cell_contents  # 第一个外部变量
'Foo'
>>> printer.__closure__[1].cell_contents  # 第二个外部变量
'Bar'

__call__

object.__call__(self[, args…])
Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...)
.

read more

  • PEP 318 -- Decorators for Functions and Methods

  • Python Decorator Library

  • Python Tips: Decorators

  • Python Closures

  • Charming Python: Decorators make magic easy

  • Decorators and Functional Python

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容