Reputation: 1508
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")
Upvotes: 0
Views: 47
Reputation: 168863
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
Upvotes: 2