2017-02-26 6 views
2

私は興味深いシナリオに遭遇しましたが、デコレータをPythonで作成しています。以下は私のコードです: - 「obj_userは」飾ら関数の引数として渡された場合、上記のコードに示すようにPythonのデコレータとしてクラス内でstaticmethodを作る方法は?

class RelationShipSearchMgr(object): 

    @staticmethod 
    def user_arg_required(obj_func): 
     def _inner_func(**kwargs): 
      if "obj_user" not in kwargs: 
       raise Exception("required argument obj_user missing") 

      return obj_func(*tupargs, **kwargs) 

     return _inner_func 

    @staticmethod 
    @user_arg_required 
    def find_father(**search_params): 
     return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params) 

、私は、チェックする、(クラスの静的メソッドである)デコレータを作成しました。私は機能find_fatherを装飾しましたが、次のエラーメッセージが表示されています: - 'staticmethod' object is not callable

pythonのデコレータとして上記のような静的ユーティリティメソッドを使用する方法は?

ありがとうございます。

+1

この回答の助けをしていますか? http://stackoverflow.com/a/6412373/4014959 –

答えて

2

staticmethodは、記述子である。 @staticmethodfunctionの代わりにディスクリプタオブジェクトを返します。それはなぜそれが発生するstaticmethod' object is not callable

私の答えはこれを避けるだけです。 user_arg_requiredを静的メソッドにする必要はないと思います。

デコレータとして静的メソッドを使用したい場合、ハッキングがあることがわかりました。

@staticmethod 
@user_arg_required.__get__(0) 
def find_father(**search_params): 
    return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params) 

この文書では、ディスクリプタとは何かを説明します。ビットを掘削した後

https://docs.python.org/2/howto/descriptor.html

0

、Iはstaticmethodオブジェクトを実行する生関数を記憶__func__内部変数__func__を有することを見出しました。

だから、次のソリューションは、私の仕事: -

@staticmethod 
@user_arg_required.__func__ 
def find_father(**search_params): 
    return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params) 
関連する問題