What's the best way to pass a method and a method parameter to another method?
Is there a better way to do the following?
def method1(name)
return 'Hello ' + name
def method2(methodToCall, methodToCallParams, question):
greetings = methodToCall(methodToCallParams)
return greetings + ', ' + question
method2(method1, 'Sam', 'How are you?')
If you want to package the invocation up in one hit, you can use the functools module:
from functools import partial
def some_function(param_one, param_two):
print "Param One: %s" % param_one
print "Param Two: %s" % param_two
def calling_function(target):
target()
calling_function(partial(some_function, "foo", "bar"))
You can do tweakier things with functools.partial too, such as binding only some parameters, leaving you with a function with a new signature. It's overkill in a lot of cases to use it but it certainly has it's place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With