Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Are instance methods first-class objects?

In python, is there a way of doing the following?

for method in list_of_methods:
   class_instance.method(data)

I would think this to be possible in python, since many things are 1st class objects.

Edit:
Using some comments below, I tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Class_Test:
    def __init__(self):
        pass
    
    def method1(self, data):
        print(f"Method 1: {data}")
    def method2(self,data):
        print(f"Method 1: {data}")
        
list_of_methods = ["method1","method2"]
for method in list_of_methods:
    getattr(Class_Test(),method)("inside for loop")

>Solution :

If list_of_methods is a list of strings of method names, use getattr to get the bound instance method by name, then call it.

for method in list_of_methods:
    getattr(class_instance, method)(data)

If, instead, list_of_methods is a list of unbound methods from the same class,

for method in list_of_methods:
    method(class_instance, data)

I.e.,

class Animal:
    def __init__(self, name):
        self.name = name

    def make_sound(self, volume):
        print(f"{self.name} makes a sound at volume {volume}")


list_of_animals = [Animal("Puppo"), Animal("Catto")]
list_of_method_names = ["make_sound"]
list_of_methods = [Animal.make_sound]

for animal in list_of_animals:
    for method_name in list_of_method_names:
        getattr(animal, method_name)(15)
    for method in list_of_methods:
        method(animal, 24)

prints out

Puppo makes a sound at volume 15
Puppo makes a sound at volume 24
Catto makes a sound at volume 15
Catto makes a sound at volume 24
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading