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, ...)
.