2017-11-30 12 views
0

私はこのようなシンプルなデコレータを持っています。しかし、私はPythonファイルをインポートするとすぐに実行され、私は再び関数を呼び出すことはできません。デコレータはどのように使用されるのですか?別のファイルでデコレータを読み込んで使用する

def plain_decorator(func): 
    def decorated_func(): 
     print "Decorating" 
     func() 
     print "Decorated" 
    return decorated_func() 

@plain_decorator 
def hw(): 
    print "Hello Decorators!" 

>>> import decorator_ex2 as d 
Decorating 
Hello Decorators! 
Decorated 
>>> d.hw() 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
TypeError: 'NoneType' object is not callable 
>>> 

答えて

2

あなたが外(plain_decorator)関数から

def plain_decorator(func): 
    def decorated_func(): 
     print "Decorating" 
     func() 
     print "Decorated" 
    return decorated_func 

@plain_decorator 
def hw(): 
    print "Hello Decorators!" 
を返すとき、あなたの内側(decorated_func)関数を呼び出しているので、その、これを使用してみてください
関連する問題