2017-02-26 31 views
2

我遇到了一個有趣的場景,同時在python中創建裝飾器。以下是我的代碼: -如何使類中的staticmethod作爲裝飾器在python中?

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) 

如上面的代碼所示,我創建了一個裝飾(這是在類的靜態方法),檢查,如果「obj_user」作爲參數傳遞給裝飾函數傳遞。我已裝飾功能find_father,但我收到以下錯誤消息: - 'staticmethod' object is not callable

如何使用上面顯示的靜態工具方法作爲python中的裝飾器?

在此先感謝。

+1

這是否回答幫助? http://stackoverflow.com/a/6412373/4014959 –

回答

2

staticmethod描述符@staticmethod返回描述符對象而不是function。那爲什麼它提出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

挖一點後,我發現,靜態方法對象具有__func__內部變量__func__,其存儲將要執行的原始功能。

所以,下面的解決方案爲我工作: -

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