سؤال

I want to create a method (set) that injects arguments into another (set_result). I've tried this using partial as below.

from functools import partial

class MyClass(MyClassParent):
    set = partial(MyClassParent.set_result, None)

But this doesn't work. When calling set on an instance of MyClass I get this error:

TypeError: set_result() takes exactly 2 arguments (1 given)

I assume this means the implicit self is not passed. If I write set like this it works:

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

How can I wrap set_result using the former method?

هل كانت مفيدة؟

المحلول 3

The reason this doesn't work is that functools.partial is not a descriptor. Accessing it on an instance will not return a bound method.

There's a Python bug on the tracker for this, to which I submitted a patch.

نصائح أخرى

set = staticmethod(partial(MyClassParent.set_result, None))
class MyClass(MyClassParent):
    set = partial(MyClassParent.set_result, MyClassParent, None)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top