bmaz bmaz - 4 months ago 6
Python Question

Pass a method to a function before object instantiation in python

I have a class called "App" which has several methods. I want to write a function which creates several instances of App and use one of those methods for each instance. How can I pass the method name as argument to the function ?

Code example:

class App(object):

def __init__(self, id):
self.id = id

def method_1(self):
result1 = self.id + 1
return result1

def method_2(self):
result2 = self.id + 2
return result2

def use_method_for_each_instance(method):
all_results = []
for id in id_list:
app_instance = App(id)
all_results.append(app_instance.method())
return all_results

id_list = [1,2,3]
use_method_for_each_instance(method_1)


With this code I get "NameError: name 'method_1' is not defined", which is logical since method_1 is only defined when an "App" object is created.
Can you help me to change my code in order to avoid that error?

Answer

You can use function from class namespace.

def use_method_for_each_instance(method):
    all_results = []
    for id in id_list:
        app_instance = App(id)
        all_results.append( method(app_instance) )
    return all_results

id_list = [1,2,3]
use_method_for_each_instance(App.method_1)
Comments