Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a method to a function before object instantiation in python

Tags:

python

oop

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?

like image 508
bmaz Avatar asked Mar 13 '26 19:03

bmaz


2 Answers

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)
like image 145
Arnial Avatar answered Mar 15 '26 13:03

Arnial


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")
like image 22
Moses Koledoye Avatar answered Mar 15 '26 12:03

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!