Python: call all methods of an object with a given set of arguments

I would like to call all methods of an instance of a python object with a given set of arguments, i.e. for an object of type

class Test():
    def a(input):
        print "a: " + input
    def b(input):
        print "b: " + input
    def c(input):
        print "c: " + input

I would like to write a dynamic method to run

myMethod('test')

as a result

a: test
b: test
c: test

by repeating all test () methods. Thanks in advance for your help!

+5
source share
2 answers

It is not clear why you want to do this. Usually in something like unittest you should enter input in your class and then reference it inside each test method.

Use validation and export.

from inspect import ismethod

def call_all(obj, *args, **kwargs):
    for name in dir(obj):
        attribute = getattr(obj, name)
        if ismethod(attribute):
            attribute(*args, **kwargs)

class Test():
    def a(self, input):
        print "a: " + input
    def b(self, input):
        print "b: " + input
    def c(self, input):
        print "c: " + input

call_all(Test(), 'my input')

Conclusion:

a: my input
b: my input
c: my input
+10
source

. Python : . unittest doctest .

- :

def call_everything_in(an_object, *args, **kwargs):
    for item in an_object.__dict__:
        to_call = getattr(an_object, item)
        if callable(to_call): to_call(*args, **kwargs)
+1

All Articles