简体   繁体   中英

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.

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)

Try creating a partial from an instance of A .

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

You can then call FUNC like so:

FUNC(A(4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM