Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/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 在类定义处包装另一个方法_Python_Class_Properties_Python 3.x_Instance Methods - Fatal编程技术网

Python 在类定义处包装另一个方法

Python 在类定义处包装另一个方法,python,class,properties,python-3.x,instance-methods,Python,Class,Properties,Python 3.x,Instance Methods,我想创建一个方法(set),将参数注入另一个(set\u result)。我用partial试过了,如下所示 from functools import partial class MyClass(MyClassParent): set = partial(MyClassParent.set_result, None) 但这不起作用。在MyClass的实例上调用set时,我得到以下错误: TypeError: set_result() takes exactly 2 argument

我想创建一个方法(
set
),将参数注入另一个(
set\u result
)。我用
partial
试过了,如下所示

from functools import partial

class MyClass(MyClassParent):
    set = partial(MyClassParent.set_result, None)
但这不起作用。在
MyClass
的实例上调用
set
时,我得到以下错误:

TypeError: set_result() takes exactly 2 arguments (1 given)
我假设这意味着隐式
self
未被传递。如果我这样写
,它会工作:

def __init__(self, *args, **kwds):
    super().__init__(*args, **kwds)
    self.set = partial(self.set_result, None)

如何使用前一种方法包装
set\u result

这不起作用的原因是
functools.partial
不是描述符。在实例上访问它不会返回绑定方法

set = staticmethod(partial(MyClassParent.set_result, None))

跟踪程序中有一条Python,我向它提交了一份报告。

我不确定这是OP想要的。考虑到他的第二个版本工作正常。这将创建一个版本的set_result,它有一个None self,并且仍然需要接受一个参数。第二个版本有什么问题?这是正确的方法。
set\u result
的签名是什么?@Marcin:我不明白为什么我不能更简洁地绑定它,并且在“运行时”的开销更少。如果我可以使用partial做包装,那么“包装”是从C完成的。我不认为
self.set=partial(self.set\u result,None)
set=partial(MyClassParent.set\u result,None)
更简洁,担心“运行时开销”听起来像是过早的优化。
class MyClass(MyClassParent):
    set = partial(MyClassParent.set_result, MyClassParent, None)