0

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:

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")
An old man in the sea.
  • 1,169
  • 1
  • 13
  • 30
  • That would be `getattr(class_instance, method_name)(data)` – jonrsharpe Sep 28 '22 at 13:38
  • Does this answer your question? [Calling a function of a module by using its name (a string)](https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string) – Kris Sep 28 '22 at 13:39

1 Answers1

2

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
AKX
  • 152,115
  • 15
  • 115
  • 172