Run All Functions In Class
Solution 1:
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
Solution 2:
This is the easiest way to solve this problem, also it's kind of flexible to do changes in it.
import threading
from threading import Thread
class ClassName():
def func1(self):
print ('2')
def func2(self):
print ('3')
def runall(self):
if __name__ == '__main__':
Thread(target = self.func1).start()
Thread(target = self.func2).start()
run = ClassName()
run.runall() # will run all the def's in the same time
Solution 3:
You can get list of all 'public' methods of your instance:
x = Foo('hi','bye')
public_method_names = [method for method in dir(x) if callable(getattr(x, method)) if not method.startswith('_')] # 'private' methods start from _
for method in public_method_names:
getattr(x, method)() # call
See more about getattr
Actually, Python doesn't have public
or private
semantic, you can read that if interested
Solution 4:
While I realize it's not what you're asking, I think what you're asking (execute all methods) in general is a bad idea, because the object's API is not internal to the object. (E.g. the user has to write functionality (namely exactly the functionality that you're asking for) in order to use the class.)
You're much better off defining a list of methods that you want to run yourself. E.g.:
exec_methods = ["bar", "foobar"]
for method in exec_methods:
getattr(x, method)()
Solution 5:
While I do not particularly recommend calling all the methods on an object since as soon as you add some that require an argument it will obviously fail, you could use a decorator to label the methods that represent a test case and then search for all the ones that have said label:
def tester_method(f):
f._is_for_test = True #add an arbitrary attribute to the function, completely supported for exactly this reason.
return f
def call_all_tester_methods(x):
"""finds all attributes with a ._is_for_test attribute of their
own and calls all of them in no guaranteed order"""
methods = {}
for name in dir(x):
attr = getattr(x,name)
if getattr(attr,"_is_for_test",False):
methods[name] = attr
for name,method in methods.items():
#print("calling: {}".format(name))
method()
class Foo(object):
def __init__(self,a,b):
self.a = a
self.b=b
@tester_method
def bar(self):
print(self.a)
@tester_method
def foobar(self):
print(self.b)
def othermethod_not_for_test(self,arg):
return self.a + arg #this is not included in the test case
obj = Foo('hi','bye')
call_all_tester_methods(obj)
Post a Comment for "Run All Functions In Class"