-1

Consider the following example:

class foo:
    def __init__(self):
        print ("Constructor")
    def testMethod(self,val):
        print ("Hello " + val)
    def test(self):
        ptr = self.testMethod("Joe") <---- Anyway instead of calling self.testMethod with parameter "Joe" I could simple bind the parameter Joe to a variable ?
        ptr()

k = foo()
k.test()

In the defintion test is it possible for me to create a variable which when called calls the method self.testMethod with the parameter "Joe" ?

James Franco
  • 4,516
  • 10
  • 38
  • 80
  • Why is this a downvote now ? Anyway i could improve this ? Downvoting without a clue isnt really productive – James Franco Jul 28 '16 at 22:04
  • You mean something like: `def test(self, name): ptr=self.testMethod(name)` ? Then you can call k.test("Joe") – marcanuy Jul 28 '16 at 22:07
  • 4
    You mean like `from functools import partial`, then `self.callable = partial(self.testMethod, 'Joe')`? – Martijn Pieters Jul 28 '16 at 22:10
  • yes partial is what I am looking equivalent to std::bind in C++ – James Franco Jul 28 '16 at 22:11
  • I would love to know why someone gave me a downvote though on a totally logical question – James Franco Jul 28 '16 at 22:16
  • Not my downvote, but insofar as the problem appears to have only come up in the first place on account of searching the docs using C++ terminology ("binder") instead of functional programming terminology ("partial"), I could see someone from the FP world being annoyed at it. But I think that makes it a good and useful question even as a duplicate; not everyone _does_ know functional terminology. – Charles Duffy Aug 14 '22 at 21:50

2 Answers2

1

You could pass a name to the constructor (and store it on the class instance), this is then accessible to methods:

class Foo:
    def __init__(self, name):
        print("Constructor")
        self.name = name

    def testMethod(self):
        print("Hello " + self.name)

    def test(self):
        self.testMethod()

As follows:

k = Foo("Joe")
k.test()          # prints: Hello Joe
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • Not really. I am looking for binding functionality. I dont want any other approach. The code i just posted is a simple example. – James Franco Jul 28 '16 at 22:09
1

Either use a functools.partial() object or a lambda expression:

from functools import partial

ptr = partial(self.testMethod, 'Joe')

or

ptr = lambda: self.testMethod('Joe')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343