echinbic
echinbic

Reputation: 89

How to loop over all functions of another class using a list of function type elements?

I am trying to get a list of all the functions in a class and then looping over them so they are all executed without having to type each one out. For example:

class Foo:
    def foo(self):
        print('foo')

    def bar(self):
        print('bar')

Then in another file

import Foo
import inspect

newfoo = Foo()
functions = [f for f in inspect.getmembers(Foo, predicate=inspect.isfunction)]
for f in functions:
    newfoo.f[1]()

I am hoping to get:

foo
bar

But this gives the error

AttributeError: 'Foo' object has no attribute 'f'

Any ideas on how to execute this? Thanks in advance.

Upvotes: 0

Views: 152

Answers (3)

Jan
Jan

Reputation: 43169

You could even use it without the inspect module:

class Foo:
    def foo():
        print('foo')

    def bar():
        print('bar')


object_methods = [method_name for method_name in dir(Foo)
                  if not method_name.startswith("__") and
                  callable(getattr(Foo, method_name))]


print(object_methods)

This yields

['bar', 'foo']

Upvotes: 1

MAHBOD NOURI
MAHBOD NOURI

Reputation: 106

Your code is almost correct. just change newfoo.f[1]() to f[1]() and it will work properly.

for f in functions:
    f[1]()

Upvotes: 0

leaf_soba
leaf_soba

Reputation: 2518

You can use getattr to call class method by name.

code:

import inspect
class Foo:
    def foo(self):
        print('foo')

    def bar(self):
        print('bar')

newfoo = Foo()
functions = [f for f in inspect.getmembers(Foo, predicate=inspect.isfunction)]
for f in functions:
    getattr(newfoo, f[0])()

result:

bar
foo

Upvotes: 2

Related Questions