Calling an arbitrary class method for many objects

Viewed 57

I want to create a generic function to call specific class methods for every object within a list. For example, say we have objects a, b, and c that all have methods eat(), sleep(), and code().

My goal is to create

def do_all(fn, objs):
    for obj in objs:
        obj.fn()

Such that I can call do_all(eat, [a,b,c]) or do_all(sleep, [a,b,c]). Note that each object is not necessarily from the same class -- they each inherit and override certain methods, and thus eat/sleep/code all perform different actions.

Currently I have many functions for each method within the class. e.g.

def eat_all(objs):
    for obj in objs:
        obj.eat()

However, I feel like there must be a better way. Any help would be great!

0 Answers
Related