Is it possible to pass a method as a parameter to a method?
self.method2(self.method1) def method1(self): return 'hello world' def method2(self, methodToRun): result = methodToRun.call() return result
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Since you asked about methods, I’m using methods in the following examples, but note that everything below applies identically to functions (except without the
selfparameter).To call a passed method or function, you just use the name it’s bound to in the same way you would use the method’s (or function’s) regular name:
Note: I believe a
__call__()method does exist, i.e. you could technically domethodToRun.__call__(), but you probably should never do so explicitly.__call__()is meant to be implemented, not to be invoked from your own code.If you wanted
method1to be called with arguments, then things get a little bit more complicated.method2has to be written with a bit of information about how to pass arguments tomethod1, and it needs to get values for those arguments from somewhere. For instance, ifmethod1is supposed to take one argument:then you could write
method2to call it with one argument that gets passed in:or with an argument that it computes itself:
You can expand this to other combinations of values passed in and values computed, like
or even with keyword arguments
If you don’t know, when writing
method2, what argumentsmethodToRunis going to take, you can also use argument unpacking to call it in a generic way:In this case
positional_argumentsneeds to be a list or tuple or similar, andkeyword_argumentsis a dict or similar. Inmethod2you can modifypositional_argumentsandkeyword_arguments(e.g. to add or remove certain arguments or change the values) before you callmethod1.