1

I have got a class similar to

class C:
    def __init__(self, a):
        self.a = a
    def noParam(self):
        return self.a
    def withParam(self, b)
        return self.a + b
instC = C(5.)

I need to pass a method of a particular instance of a class as a parameter. Passing instC.noParam works fine, but how do I pass instC.withParam with b always equal to say 239? Thanks.

Yulia V
  • 3,507
  • 10
  • 31
  • 64

2 Answers2

12

You want to use functools.partial:

import functools

instC = C(5.)
meth = functools.partial(instC.withParam, 239)

Then you can pass this method (bound with both your instance and the value 239):

do_thing(meth)
Nick Bastin
  • 30,415
  • 7
  • 59
  • 78
7

You can use lambda functions to bind parameters:

meth = lambda: instC.withParam(239)

aldeb
  • 6,588
  • 5
  • 25
  • 48