I'd like to call all methods of a python object instance with a given set of arguments, i.e. for an object like
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 allowing me to run
myMethod('test')
resulting in
a: test
b: test
c: test
by iterating over all test()-methods. Thanks in advance for your help!
Not exactly sure why you want to do this. Normally in something like unittest you would provide an input on your class then reference it inside each test method.
Using inspect and dir.
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')
Output:
a: my input
b: my input
c: my input
You really don't want to do this. Python ships with two very nice testing frameworks: see the unittest
and doctest
modules in the documentation.
But you could try something like:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With