Reputation: 31
I have an issue, I'd like to have a function that calls or executes all functions inside a class.
class example:
def foo(self):
print("hi")
def bar(self):
print("hello")
def all(self):
self.foo()
self.bar()
Is there any better way to do this? Since my class has around 20 functions and I want just one function to call all of them. Thanks
Upvotes: 1
Views: 461
Reputation: 7441
I put this together and tested it and it seems to work and does not need any libraries and follows your original intent:
class example:
def __init__(self):
n = self.__class__.__name__
self.method_list = [func for func in dir(eval(n)) \
if callable(getattr(eval(n), func)) \
and func[0]!='_' \
and func!='run_all']
def foo(self):
print("hi")
def bar(self):
print("hello")
def run_all(self):
for m in self.method_list:
runstring = 'self.' + m + '()'
eval(runstring)
Using it:
>> a = example()
>> a.run_all()
hello
hi
all
is a Python command so I renamed your method to run_all
.
func!='run_all'
was necessary so you don't get a nasty recursion situation happening.
This lets you list the methods, I restricted it just so that no private methods get listed.
self.__class__.__name__
gets the name of your class
Upvotes: 0
Reputation: 3775
See How do I get list of methods in a Python class? to how enlist method with inspect or dir
While all are ugly, inspection is the prefered methods. You can invoke all the methods of an object via inspect
import inspect
class A:
def h(self):
print ('hellow')
def all(self):
for name, f in inspect.getmembers(self, predicate=inspect.ismethod):
if name != 'all' and not name.startswith('_'):
f()
a = A()
a.all()
If prefer dir you can try - catch getattr(self, attr)()
for attr in dir(self):
try:
getattr(self, attr)()
except Exception:
pass
Upvotes: 1
Reputation: 152
Although I am not sure if that's the best way to do it, i suggest the following
class AClass():
def my_method_1(self):
print('inside method 1')
def my_method_2(self):
print('inside method 2')
def run_my_methods():
executor = AClass()
all_methods = dir(executor)
#separate out the special functions like '__call__', ...
my_methods = [method for method in all_methods if not '__' in method]
for method in my_methods:
eval('executor.%s()'%method)
run_my_methods()
Output is
inside method 1
inside method 2
Upvotes: 0