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

还看到:

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


当前回答

有这样一种方法:

[getattr(obj, m) for m in dir(obj) if not m.startswith('__')]

在处理类实例时,也许返回一个包含方法引用的列表,而不是仅仅返回名称¹会更好。如果这是你的目标,还有

使用不导入 从列表中排除私有方法(例如__init__)

这可能会有用。你可能还想确保它是可调用的(getattr(obj, m)),因为dir返回obj中的所有属性,而不仅仅是方法。

简而言之,对于一个班级来说

class Ghost:
    def boo(self, who):
        return f'Who you gonna call? {who}'

我们可以检查实例检索

>>> g = Ghost()
>>> methods = [getattr(g, m) for m in dir(g) if not m.startswith('__')]
>>> print(methods)
[<bound method Ghost.boo of <__main__.Ghost object at ...>>]

所以你可以马上调用它:

>>> for method in methods:
...     print(method('GHOSTBUSTERS'))
...
Who you gonna call? GHOSTBUSTERS

¹一个用例:

我使用它进行单元测试。有一个类,其中所有方法都执行相同过程的变体——这导致了冗长的测试,每个方法与其他方法之间只有细微的差别。DRY是一个遥远的梦想。

我想我应该有一个单一的测试所有的方法,所以我做了上面的迭代。

尽管我意识到我应该重构代码本身,无论如何都是符合dry的…这可能在未来仍然服务于一个随机的挑剔的灵魂。

其他回答

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

有这样一种方法:

[getattr(obj, m) for m in dir(obj) if not m.startswith('__')]

在处理类实例时,也许返回一个包含方法引用的列表,而不是仅仅返回名称¹会更好。如果这是你的目标,还有

使用不导入 从列表中排除私有方法(例如__init__)

这可能会有用。你可能还想确保它是可调用的(getattr(obj, m)),因为dir返回obj中的所有属性,而不仅仅是方法。

简而言之,对于一个班级来说

class Ghost:
    def boo(self, who):
        return f'Who you gonna call? {who}'

我们可以检查实例检索

>>> g = Ghost()
>>> methods = [getattr(g, m) for m in dir(g) if not m.startswith('__')]
>>> print(methods)
[<bound method Ghost.boo of <__main__.Ghost object at ...>>]

所以你可以马上调用它:

>>> for method in methods:
...     print(method('GHOSTBUSTERS'))
...
Who you gonna call? GHOSTBUSTERS

¹一个用例:

我使用它进行单元测试。有一个类,其中所有方法都执行相同过程的变体——这导致了冗长的测试,每个方法与其他方法之间只有细微的差别。DRY是一个遥远的梦想。

我想我应该有一个单一的测试所有的方法,所以我做了上面的迭代。

尽管我意识到我应该重构代码本身,无论如何都是符合dry的…这可能在未来仍然服务于一个随机的挑剔的灵魂。

这也是可行的:

在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。

有dir(theobject)方法列出对象的所有字段和方法(作为元组)和inspect模块(作为codeape编写)列出字段和方法及其文档(在""")。

因为在Python中可能调用所有内容(甚至字段),所以我不确定是否有一个内置函数只列出方法。您可能想要尝试通过dir获取的对象是否可调用。

你可以使用我创建的函数。

def method_finder(classname):

    non_magic_class = []

    class_methods = dir(classname)

    for m in class_methods:

        if m.startswith('__'):

            continue

        else:

            non_magic_class.append(m)

    return non_magic_class




method_finder(list)

输出:

['append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']