5

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!

2 Answers 2

12

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
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you. I will use this kind of pattern for a rule evaluation task, not for unit- or doctesting.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.