2015-04-23 84 views
6

我爲公共庫創建了一個小包裝模塊,庫有很多重複,在創建對象後,可能方法需要相同的數據元素。在Python中裝飾方法

我必須在我的包裝類中傳遞相同的數據,但並不是真的想一遍又一遍地傳遞相同的東西。所以我想將數據存儲在我的包裝類中,如果它不包含在方法中,就應用它。然而,如果事情變得毛骨悚然,我希望方法參數覆蓋類默認值。這是一段代碼片段,可以說明我的目標。

class Stackoverflow(): 
    def __init__(self,**kwargs): 
     self.gen_args = {} 
     #Optionally add the repeated element to the object 
     if 'index' in kwargs: 
      self.gen_args['index'] = kwargs['index'] 
     if 'doc_type' in kwargs: 
      self.gen_args['doc_type'] = kwargs['doc_type'] 

    #This is where the problem is   
    def gen_args(fn): 
     def inner(self,*args,**kwargs): 
      kwargs.update(self.gen_args) 
      return fn(*args,**kwargs) 
     return inner 

    #There is a bunch of these do_stuffs that require index and doc_type 
    @gen_args 
    def do_stuff(self,**kwargs): 
     print(kwargs['index']) 
     print(kwargs['doc_type']) 

#Just send arguments up with the method 
print("CASE A")   
a = Stackoverflow() 
a.do_stuff(index=1,doc_type=2) 

#Add them to the class and have all methods use them without having to specify 
#them each time 
print("CASE B") 
b = Stackoverflow(index=1,doc_type=2) 
b.do_stuff() 

#The arguments specified in the method should overwrite class values 
print("CASE C") 
c = Stackoverflow(index=1,doc_type=2) 
c.do_stuff(index=3,doc_type=4) 

編輯:

所以現在的問題是,我該如何解決gen_args還是有更好的方式來做到這一點?特定的錯誤我使用此代碼得到的是: 返回FN(* ARGS,** kwargs) 類型錯誤:do_stuff()失蹤1個人需要的位置參數: '自我'

+1

你的問題是什麼? –

+0

更新後的帖子,上面的設備顯然不起作用,所以顯而易見的問題是如何讓它做我想做的事情。 – browskie

+0

它如何失敗?它會產生錯誤信息,還是會產生不正確的結果?你期望輸出什麼,你實際得到了什麼輸出? –

回答

5

我可能會使用的inner這個定義:

def inner(self,*args,**kwargs): 
     return fn(self, *args,**dict(self.gen_args, **kwargs)) 

注:

  • 該版本提供self,這是在你的版本失蹤。
  • 優先考慮傳入的kwargs
+0

啊哈......我明白你在那裏做了什麼。我甚至沒有想到kwargs的優先級。非常好。謝謝 – browskie