2016-05-14 7 views
0

装飾された関数にいくつかのアクションを挿入したいのですが、その関数のコードに触れたくありません。デコレータを定義するときにアクションを挿入できますか?削除しないだけを追加する。装飾された関数内にいくつかのアクションを挿入する方法はありますか?

def real_decorator(func): 
    def __decorator(): 
     print 'enter the func' 
     func() # <- Can I insert some action inside this from here? 
     print 'exit the func' 
    return __decorator 


@real_decorator 
def decorated_function(): 
    print "I am decorated" 


decorated_function() 
+0

挿入アクションではどういう意味ですか? decorated_function内の特定の行に追加コードを実行しますか? – Schore

+0

はい、コードフレームにアクセスして、実際にデザインを再考したいと思っています。デコレータは* any *関数と共に使用することを意図しており、ランダムなコードを追加することで、明らかな損害を引き起こす可能性があります。だから問題は、なぜあなたはこれをしたいのですか? – cdarke

答えて

1

どういうことですか?

def real_decorator(func): 

    def __decorator(): 
     print 'enter the func' 
     for action in __decorator.extra_actions: 
      action() 
     func() 
     print 'exit the func' 

    __decorator.extra_actions = [] 

    return __decorator 

@real_decorator 
def decorated_function(): 
    print "I am decorated" 

decorated_function() 

def new_action(): 
    print "New action" 

decorated_function.extra_actions.append(new_action) 

decorated_function() 
関連する問題