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
添加回答
舉報
