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?
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)
You can pass the name of the method as a string and then you can use getattr to retrieve the method from your app_instance.
Like so:
def use_method_for_each_instance(method):
for id in id_list:
app_instance = App(id)
method_to_call = getattr(app_instance, method)
# ^ gets callable method from instance
all_results.append(method_to_call())
return all_results
use_method_for_each_instance("method_1")
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