Search code examples
pythonclassjython

Executing a list of methods with list of objects


I have got a list of Objects of the same class and want to execute a list of methods one by one.

F.e.

objectlist = [ obj1, obj2, obj3, ...]
methodlist = [ obj(?).returnstring(para1), obj(?).returnint(para2,subpara1), ...]

for i in range(len(objectlist)):
    for n in range(len(methodlist)):
        value = obj[i].methodlist[n]
        print(value)

I just have this dirty workaround:

objectlist = [ obj1, obj2, obj3, ...]
i = 0
methodlist = [ objectlist[i].returnstring(para1), objectlist[i].returnint(para2,subpara1), ...]

for i in range(len(objectlist)):
    for n in range(len(methodlist)):
        value = obj[i].methodlist[n]
        print(value)

Well ... it works, but I get stomachache with this solution.

Is there a nicer way to do this?

Greets,

zonk


Solution

  • Your workaround does not work, it only will call on the first element. Since i = 0, it will evaluate instantly.

    You can use lambda-expressions for this:

    objectlist = [ obj1, obj2, obj3, ...]
    methodlist = [lambda obj:obj.returnstring(para1), lambda obj:obj.returnint(para2,subpara1), ...]
    

    So here methodlist contains a list of lambda expressions of the form:

    lambda obj:obj.returnstring(para1)
    

    A lambda expression is an anonymous function that here takes as input a parameter obj and *returns obj.returnstring(para1) on that object. It is thus more or less equivalent to:

    def afunction(obj):
        return obj.returnstring(para1)
    

    Now you can simply iterate over the list of objects and methods and call the lambda expression with the parameter and do something with the result. Like:

    for i in range(len(objectlist)):
        for n in range(len(methodlist)):
            value = methodlist[n](obj[i])
            print(value)
    

    But it is more elegantly to loop immediately over your elements like:

    for obji in objectlist:
        for methn in methodlist:
            value = methn(obji)
            print(value)