2016-07-23 69 views
-1

我想了解Python的裝飾,並寫了這個代碼:例裝飾錯誤

def hello_world(fn): 
    print('hello world') 
    fn() 
    pass 

@hello_world 
def decorate(): 
    print('hello decoatrion') 
    return 

decorate() 

我的目標是前「你好裝飾」打印「世界你好」,但輸出如下:

hello world 
hello decoatrion 
Traceback (most recent call last): 
    File "test_decortor.py", line 11, in <module> 
    decorate() 
TypeError: 'NoneType' object is not callable 
+0

好的,那你有什麼問題? – melpomene

+0

[我如何在Python中創建一個函數裝飾器鏈?](http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in -python) – GingerPlusPlus

+0

你的裝飾器正在返回'None',而不是裝飾函數。查看[這些示例](https://docs.python.org/3/whatsnew/2.4.html#pep-318-decorators-for-functions-and-methods),以及[PEP 318 - 裝飾器函數,方法和類](https://www.python.org/dev/peps/pep-0318/)本身。 – martineau

回答

3

裝飾語法速記

decorated = decorate(decorated) 

所以,如果您有:

def hello_world(fn): 
    print('hello world') 
    fn() 
    pass 

def decorate(): 
    print('hello decoatrion') 
    return 

decorate = hello_world(decorate) 

您應該看到的問題是什麼(也注意到, pass這裏什麼都不做)。

def hello_world(fn): 
    def says_hello(): 
     print('hello world') 
     return fn() 
    return says_hello 

def decorate(): 
    print('hello decoration') 

decorate = hello_world(decorate) 

會做你想做的。或者你可以這樣寫:

@hello_world 
def decorate(): 
    print('hello decoration') 
+0

文檔參考:https://docs.python.org/3/reference/compound_stmts.html#function-definitions – melpomene

3

裝飾者必須返回裝飾函數。你可能想沿着這些路線的東西:

def hello_world(fn): 
    def inner(): 
     print('hello world') 
     fn() 
    return inner 

@hello_world 
def decorate(): 
    print('hello decoatrion') 
    return 

decorate() 
#output: hello world 
#  hello decoatrion