Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run all functions in class

Tags:

python

class

I am trying to run all the functions in my class without typing them out individually.

class Foo(object):
    def __init__(self,a,b):
        self.a = a
        self.b=b

    def bar(self):
        print self.a

    def foobar(self):
        print self.b

I want to do this but with a loop, because my actual class has about 8-10 functions.

x = Foo('hi','bye')
x.bar()
x.foobar()
like image 695
collarblind Avatar asked May 06 '16 15:05

collarblind


1 Answers

You can use dir() or __dict__ to go through all of an object's attributes. You can use isinstance() and types.FunctionType to tell which ones are functions. Just call any that are functions.

Update

As Tadhg commented, inspect.ismethod seems like the best choice. Here's some example code:

import inspect
from itertools import ifilter


class Foo(object):
    def foo1(self):
        print('foo1')

    def foo2(self):
        print('foo2')

    def foo3(self, required_arg):
        print('foo3({!r})'.format(required_arg))

f = Foo()
attrs = (getattr(f, name) for name in dir(f))
methods = ifilter(inspect.ismethod, attrs)
for method in methods:
    try:
        method()
    except TypeError:
        # Can't handle methods with required arguments.
        pass
like image 174
Don Kirkby Avatar answered Sep 22 '22 05:09

Don Kirkby