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

还看到:

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


当前回答

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

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

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

其他回答

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

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

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类中的所有方法

dir(className)

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

要生成一个方法列表,请将方法名称放在一个列表中,不使用通常的括号。删除名称并附加圆括号,这将调用该方法。

    def methodA():
        print("@ MethodA")

    def methodB():
        print("@ methodB")

    a = []
    a.append(methodA)
    a.append(methodB)
    for item in a:
        item()

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

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