How to use functools.partial for a class method?

Viewed 765

I'd like to apply partial from functools to a class method.

from functools import partial

class A:
    def __init__(self, i):
        self.i = i

    def process(self, constant):
        self.result = self.i * constant

CONST = 2
FUNC = partial(A.process, CONST)

When I try:

FUNC(A(4))

I got this error:

'int' object has no attribute 'i'

It seems like CONST has been exchange with the object A.

1 Answers

You're binding one positional argument with partial which will go to the first argument of process, self. When you then call it you're passing A(4) as the second positional argument, constant. In other words, the order of arguments is messed up. You need to bind CONST to constant explicitly:

FUNC = partial(A.process, constant=CONST)

Alternatively this would do the same thing:

FUNC = lambda self: A.process(self, CONST)
Related