2016-07-23 2 views
-1
내가 파이썬 장식을 이해하려고 노력 중이 야하고이 코드를 작성했습니다

:예 데코레이터 오류

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 - 함수 데코레이터 , Methods and Classes] (https://www.python.org/dev/peps/pep-0318/) 그 자체. – martineau

답변

3

데코레이터 구문은 속기 :

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

데코레이터는 장식 기능을 반환해야합니다. 당신이 그렇다면

decorated = decorate(decorated) 

에 대한

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