is there a way to bind parameter to a function variable in python?

Question:

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" ?

Asked By: James Franco

||

Answers:

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
Answered By: Andy Hayden

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')
Answered By: Martijn Pieters
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.