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()
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.
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
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