使用列出给定类的所有类方法的"最佳"方法是inspect什么?如果我像这样使用inspect.isfunctionas谓词,它可以工作getmembers
class MyClass(object):
def __init(self, a=1):
pass
def somemethod(self, b=1):
pass
inspect.getmembers(MyClass, predicate=inspect.isfunction)
Run Code Online (Sandbox Code Playgroud)
回报
[('_MyClass__init', <function __main__.MyClass.__init>),
('somemethod', <function __main__.MyClass.somemethod>)]
Run Code Online (Sandbox Code Playgroud)
但它不应该通过ismethod?
inspect.getmembers(MyClass, predicate=inspect.ismethod)
Run Code Online (Sandbox Code Playgroud)
在这种情况下返回一个空列表.如果有人能澄清正在发生的事情会很好.我在Python 3.5中运行它.
如文档中所述,inspect.ismethod将显示绑定方法.这意味着如果要检查其方法,则必须创建该类的实例.由于您正在尝试检查未实例化的类上的方法,因此您将获得一个空列表.
如果你这样做:
x = MyClass()
inspect.getmembers(x, predicate=inspect.ismethod)
Run Code Online (Sandbox Code Playgroud)
你会得到方法.