标签: python
有没有办法在Python中使用循环内的方法?如下所示:
obj=SomePythonObject() list_of_methods=dir(obj) for i in list_of_methods: try: print obj.i() except: print i,'failed'
答案 0 :(得分:2)
是的,可以使用callable和getattr:
obj=SomePythonObject() list_of_methods=dir(obj) for i in list_of_methods: try: item = getattr(obj, i, None) if callable(item): item() except: print i,'failed'