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

还看到:

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


当前回答

methods = [(func, getattr(o, func)) for func in dir(o) if callable(getattr(o, func))]

给出一个相同的列表

methods = inspect.getmembers(o, predicate=inspect.ismethod)

所做的事。

其他回答

我知道这是一篇旧文章,但只是写了这个函数,并将它留在这里,以防有人跌跌撞撞地寻找答案:

def classMethods(the_class,class_only=False,instance_only=False,exclude_internal=True):

    def acceptMethod(tup):
        #internal function that analyzes the tuples returned by getmembers tup[1] is the 
        #actual member object
        is_method = inspect.ismethod(tup[1])
        if is_method:
            bound_to = tup[1].im_self
            internal = tup[1].im_func.func_name[:2] == '__' and tup[1].im_func.func_name[-2:] == '__'
            if internal and exclude_internal:
                include = False
            else:
                include = (bound_to == the_class and not instance_only) or (bound_to == None and not class_only)
        else:
            include = False
        return include
    #uses filter to return results according to internal function and arguments
    return filter(acceptMethod,inspect.getmembers(the_class))

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

你也可以从types中导入FunctionType并使用类测试它。__dict__:

from types import FunctionType

class Foo:
    def bar(self): pass
    def baz(self): pass

def methods(cls):
    return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]

methods(Foo)  # ['bar', 'baz']

如果你的方法是“常规”方法,而不是静态方法、类方法等。 我想出了一个小窍门

for k, v in your_class.__dict__.items():
    if "function" in str(v):
        print(k)

这可以通过相应改变if条件中的“function”扩展到其他类型的方法。 在Python 2.7和Python 3.5中测试。

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

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