2015-04-23 80 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