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

advertisements

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']


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]