3 回答
TA贡献2036条经验 获得超8个赞
虽然都是丑陋的,但检查是首选方法。你可以通过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()
如果更喜欢 dir,您可以尝试 - catch getattr(self, attr)()
for attr in dir(self):
try:
getattr(self, attr)()
except Exception:
pass
TA贡献1797条经验 获得超6个赞
虽然我不确定这是否是最好的方法,但我建议如下
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()
输出是
inside method 1
inside method 2
添加回答
举报