我想通过类中的方法进行迭代,或者根据目前的方法不同地处理类或实例对象。我如何获得类方法的列表?

还看到:

方法中的方法如何列出 Python 2.5模块? 循环在 Python / IronPython对象 方法 找到方法 对象有 我怎么看里面 Python对象? 我该怎么做 中对对象进行内省 Python 2. x ? 如何获得 对象的方法和的完整列表 属性? 找出 函数可以从类中获得 实例在python中?


当前回答

Python 3。X答案没有外部库

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

dunder-excluded结果:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]

其他回答

这也是可行的:

在mymodule.py:

def foo(x):
   return 'foo'
def bar():
   return 'bar'

在另一个文件中:

import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]

输出:

(“foo”、“酒吧”)

来自Python文档:

inspect.isroutine(object)

如果对象是用户定义的或内置的函数或方法,则返回true。

试一试 print(帮助(名称)) 它输出类的方法

注意,您需要考虑是否希望结果中包含继承(但不重写)基类的方法。dir()和inspect.getmembers()操作包含基类方法,但使用__dict__属性不包含。

可以使用以下代码列出python类中的所有方法

dir(className)

这将返回类中所有方法名称的列表

就像这样

pprint.pprint([x for x in dir(list) if not x.startswith("_")])