Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.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对象以将默认值添加到方法kwargs_Python - Fatal编程技术网

修补python对象以将默认值添加到方法kwargs

修补python对象以将默认值添加到方法kwargs,python,Python,我想修补一些使用外部模块对象的代码 这个对象的一个方法被到处调用,我需要在所有这些调用中设置一个新的默认kwarg 我认为与其添加这么多重复代码,不如更改object方法。最干净的方法是什么 这是调用的,没有“干净”版本 如果需要替换类Foo中的方法bar,请使用以下代码: oldMethod = Foo.bar def newMethod(self, **kwargs): ... fix kwargs as necessary ... oldMethod(self, **kwa

我想修补一些使用外部模块对象的代码

这个对象的一个方法被到处调用,我需要在所有这些调用中设置一个新的默认kwarg

我认为与其添加这么多重复代码,不如更改object方法。最干净的方法是什么

这是调用的,没有“干净”版本

如果需要替换类
Foo
中的方法
bar
,请使用以下代码:

oldMethod = Foo.bar
def newMethod(self, **kwargs):
    ... fix kwargs as necessary ...
    oldMethod(self, **kwargs)
Foo.bar = newMethod
  • 首先,我们将旧方法句柄保存在变量中
  • 然后我们将新方法定义为一个函数。第一个参数必须是
    self
    ,就像此函数在类中一样
  • 要调用原始方法,我们使用
    oldMethod(self,…)
    。这将采用方法指针,并以实例作为第一个参数调用它
    self.oldMethod()
    不起作用,因为我们不在
    类中(我认为)
  • 最后,我们在类中安装补丁方法
  • 相关的:


    我决定编写一个包装器类,它继承我需要修改的对象

    class Wrapper(Target):
        def method(self, *args, **kwargs):
            kwargs['option'] = True
            return super(Wrapper, self).method(*args, **kwargs)
    
    instance = Target()
    instance.__class__ = Wrapper
    

    self.oldMethod
    在哪里定义/设置?作为一个装饰师,这不是更整洁吗?@sapi,如果你能够修改源代码的话。但是,我怀疑OP在这里想要的是什么,因为如果是这样的话,那么OP首先会这么做。为什么不呢:
    instance=Wrapper()
    ?在我的实际情况中,实例是由我不想编辑的外部模块的函数返回的。很可能有更好的方法可以做到这一点,尽管我对课程知之甚少。