首先正常的函数形式和调用方法:
python
>>> def foo(): ... return 1 >>> foo() 1
基本的嵌套函数形式和调用方法
函数
>>> def outer(): ... x = 1 ... def inner(): ... print x # 1 ... inner() # 2 >>> outer() 1
函数inner所定义在函数outer中。inner能够访问到他的外层函数的变量。学习
>>> issubclass(int, object) # all objects in Python inherit from a common baseclass True >>> def foo(): ... pass >>> foo.__class__ # 1 <type 'function'> >>> issubclass(foo.__class__, object) True
函数即对象,因此能够将函数当成普通的对象变量同样,能够做为普通的参数,也能够做为一个函数的返回值。spa
>>> def outer(): ... x = 1 ... def inner(): ... print x+1 ... return inner ... >>> f = outer() >>> f() 2
这里outer函数就是将inner函数返回给f
code
>>> def outer(some_func): ... def inner(): ... print 'before some_func' ... ret = some_func() ... return ret + 1 ... return inner ... >>> def foo(): ... return 1 ... >>> decorated = outer(foo) >>> decorated() before some_func 2 >>>
这里将foo函数看成参数传递给outer函数,outer函数中定义了一个inner函数,inner中调用了传递进来的foo函数,并在调用之行以前打印文字。outer函数酱inner函数返回给decorated(这里并无执行inner函数)。而后执行decorated()对象
这里decorated经过outer函数将foo函数装饰了一下(在执行以前打印一句话)blog
>>> def outer(some_func): ... def inner(): ... print 'before some_func' ... ret = some_func() ... return ret + 1 ... return inner ... >>> @outer ... def foo(): ... return 1 ... >>> foo() before some_func 2 >>>
这里再也不明确的使用调用outer将foo看成参数传递,而后用decorated接受。而直接用@outer放在foo函数定义开头,便可实现使用outer函数装饰foo的功能。以后直接调用foo便可。it
>>> def logger(func): ... def inner(*args, **kwargs): ... print "func start" ... func(*args, **kwargs) ... print "func end" ... return inner ... >>> @logger ... def foo(a, b): ... print a + b ... >>> foo(1, 2) func start 3 func end >>>
logger中定义的inner函数用*args和**kwargs接受参数,传递给func函数执行。即完整实现一个函数装饰器的功能,以后用@logger装饰函数foo,在执行foo函数时,能看到在其以前以后打印的语句。io
详细学习地址:http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/function