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

还看到:

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


当前回答

使用检查。Ismethod, dir和getattr

 import inspect
 class ClassWithMethods:
    
    def method1(self):
        print('method1')
    def method2(self):
        print('method2')

obj=ClassWithMethods()

method_names = [attr for attr in dir(obj) if inspect.ismethod(getattr(obj,attr))

print(method_names)

输出:

[[('method1', <bound method ClassWithMethods.method1 of <__main__.ClassWithMethods object at 0x00000266779AF388>>), ('method2', <bound method ClassWithMethods.method2 of <__main__.ClassWithMethods object at 0x00000266779AF388>>)]]

其他回答

如果你只想列出一个python类的方法

import numpy as np
print(np.random.__all__)

使用检查。Ismethod, dir和getattr

 import inspect
 class ClassWithMethods:
    
    def method1(self):
        print('method1')
    def method2(self):
        print('method2')

obj=ClassWithMethods()

method_names = [attr for attr in dir(obj) if inspect.ismethod(getattr(obj,attr))

print(method_names)

输出:

[[('method1', <bound method ClassWithMethods.method1 of <__main__.ClassWithMethods object at 0x00000266779AF388>>), ('method2', <bound method ClassWithMethods.method2 of <__main__.ClassWithMethods object at 0x00000266779AF388>>)]]

试试属性__dict__。

def find_defining_class(obj, meth_name):
    for ty in type(obj).mro():
        if meth_name in ty.__dict__:
            return ty

So

print find_defining_class(car, 'speedometer') 

Python第210页

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

给出一个相同的列表

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

所做的事。