首先正常的函數形式和調用方法:
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