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")
2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I really enjoyed the unbounded methods list way of doing it. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.