Home > database >  Call a function on multiple objects dynamically
Call a function on multiple objects dynamically

Time:08-07

I wonder if it is possible to dynamically call a function on multiple objects. For example:

class Obj:
    def Foo():
        print("foo")

    def Bar():
        print("bar")

a = Obj()
b = Obj()

def execute(objects, func):
    # execute func on both a & b

execute([a, b], Obj.Foo)
execute([a, b], Obj.Bar)

Note: functions cannot be called like func(obj), and need to be called like this: obj.func()

CodePudding user response:

The other answers are probably more appropriate, but you might consider: https://docs.python.org/3/library/functions.html#map

# func will be called with one parameter.
list(map(func, objects))

CodePudding user response:

You're looking for a for loop.

def execute(objects, func):
    for obj in objects:
        func(obj)

This is assuming you don't care about the result of the functions, only the side effects. If you want a list of the results, you can use a list comprehension.

def execute(objects, func):
    return [func(obj) for obj in objects]
  • Related