Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use functools.partial for a class method?

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.

like image 490
kabhel Avatar asked Dec 18 '25 07:12

kabhel


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)
like image 78
deceze Avatar answered Dec 20 '25 21:12

deceze