2016-07-23 67 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