Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中修饰方法_Python - Fatal编程技术网

在python中修饰方法

在python中修饰方法,python,Python,我正在为一个公共库制作一个小包装器模块,这个库有很多重复,在对象创建之后,可能方法需要相同的数据元素 我必须在我的包装器类中传递相同的数据,但我真的不想一次又一次地传递相同的数据。因此,我希望将数据存储在我的包装器类中,并在方法中未包含数据时应用它。然而,如果事情变得棘手,我希望方法参数覆盖类默认值。下面是一段代码片段,说明了我的目标 class Stackoverflow(): def __init__(self,**kwargs): self.gen_args = {

我正在为一个公共库制作一个小包装器模块,这个库有很多重复,在对象创建之后,可能方法需要相同的数据元素

我必须在我的包装器类中传递相同的数据,但我真的不想一次又一次地传递相同的数据。因此,我希望将数据存储在我的包装器类中,并在方法中未包含数据时应用它。然而,如果事情变得棘手,我希望方法参数覆盖类默认值。下面是一段代码片段,说明了我的目标

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,或者有更好的方法来修复gen_args?我在这段代码中遇到的具体错误是: 返回fn(*args,**kwargs)
TypeError:do_stuff()缺少1个必需的位置参数:“self”

我可能会使用
内部的这个定义:

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

  • 此版本提供了
    self
    ,这在您的版本中缺失
  • 这将优先考虑传入的
    kwargs

你的问题是什么?更新帖子,上面的装备显然不起作用,所以最明显的问题是如何让它达到我想要的效果。它怎么会失败?它是否生成错误消息,或者是否生成不正确的结果?你期望什么样的输出,你实际得到什么样的输出?问题的根源是我不确定如何编写装饰程序。我不断地按摩它,并得到与争论有关的错误。将使用此的错误消息进行更新。谢谢你的帮助,阿弥陀佛。。。。我知道你在那里做了什么。我甚至没有想到夸尔格的优先权。很不错的。非常感谢。