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

还看到:

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


当前回答

这只是一种观察。"encode"似乎是一个字符串对象的方法

str_1 = 'a'
str_1.encode('utf-8')
>>> b'a'

但是,如果在str1中检查方法,则返回一个空列表

inspect.getmember(str_1, predicate=inspect.ismethod)
>>> []

所以,也许我错了,但问题似乎并不简单。

其他回答

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

dir(className)

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

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("__")]

以上这些方法对我都没用。

我在编写pytests时遇到过这个问题。

我找到的唯一解决办法是:

1-创建另一个目录,把我所有的。py文件放在那里

2-为我的pytests创建一个单独的目录,然后导入我感兴趣的类

这允许我在类中获得最新的方法-您可以更改方法名称,然后使用print(dir(class))来确认它。

试试属性__dict__。

这只是一种观察。"encode"似乎是一个字符串对象的方法

str_1 = 'a'
str_1.encode('utf-8')
>>> b'a'

但是,如果在str1中检查方法,则返回一个空列表

inspect.getmember(str_1, predicate=inspect.ismethod)
>>> []

所以,也许我错了,但问题似乎并不简单。