在python中装饰一个方法

bro*_*kie 7 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)
Run Code Online (Sandbox Code Playgroud)

编辑:

所以问题是,我如何修复gen_args还是有更好的方法来做到这一点?我用这段代码得到的具体错误是:return fn(*args,**kwargs)TypeError:do_stuff()缺少1个必需的位置参数:'self'

Rob*_*obᵩ 5

我可能会使用这个定义inner:

    def inner(self,*args,**kwargs):
        return fn(self, *args,**dict(self.gen_args, **kwargs))
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 此版本提供self,您的版本中缺少该版本.
  • 这优先考虑传入kwargs.