Question

How do you return the results of all the methods of a class object as one list?

class Example(object):

  def Calc1(self):
     return 1

  def Calc3(self):
     return 2

  def Calc5(self):
     return 3


Desired_Result = [1,2,3]

I don't want to use the common method like this:

Desired_Result = [Example().Calc1(),Example().Calc3(),Example().Calc5()]

I want the function to be scalable in that the class can have ten or hundreds of methods, so that I wouldn't have to type each method.

Also, bonus points for getting the names of the methods as well.

Desired_Result2 = ['Calc1','Calc3','Calc5']
Was it helpful?

Solution

Try:

import inspect
# Class def here
instance = ClassDef()
methods = {m[0]: m[1] for m in inspect.getmembers(instance) if inspect.ismethod(m[1])}
method_results = {k: v() for k, v in methods.items()}  # only works for methods that take only one argument (the instance)

Note that the last line above will only work with methods that take a single argument (the instance). You can get the name combined with the result of the method as follows:

print method_results
{'Calc1': 1, 'Calc3': 2, 'Calc5': 3}

And just the results of the methods:

print [v() for v in method_results.values()]
[1, 2, 3]

OTHER TIPS

Note my comment (and now edit) on AMacK's answer. I think that answer is best. For the record, though, I originally proposed this as another viable (and now less preferable) alternative:

>>> e = Example()  # create a generic instance
>>> methods = {k: v for k, v in Example.__dict__.items() if hasattr(v, '__call__')}
>>> [v(e) for v in methods.values()]
[1, 2, 3]
>>> {k: v(e) for k, v in methods.items()}  # will only work if all methods take only one argument, the instance
{'Calc1': 1, 'Calc3': 2, 'Calc5': 3}

Note that this approach (and AMacK's current approach) will only work for methods that require one argument (the instance).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top