使用 Python `inspect` 模块列出所有 class 成员
Listing all class members with Python `inspect` module
使用 inspect
列出给定 class 的所有 class 方法的 "optimal" 方法是什么?如果我像这样
在 getmembers
中使用 inspect.isfunction
作为谓词,它会起作用
class MyClass(object):
def __init(self, a=1):
pass
def somemethod(self, b=1):
pass
inspect.getmembers(MyClass, predicate=inspect.isfunction)
returns
[('_MyClass__init', <function __main__.MyClass.__init>),
('somemethod', <function __main__.MyClass.somemethod>)]
但是它不是应该通过 ismethod
工作吗?
inspect.getmembers(MyClass, predicate=inspect.ismethod)
在这种情况下,returns 是一个空列表。如果有人可以澄清发生了什么,那就太好了。我是 运行 这个 Python 3.5.
如文档中所述,inspect.ismethod
将显示绑定方法。这意味着如果你想检查它的方法,你必须创建一个 class 的实例。由于您正在尝试检查未实例化 class 上的方法,因此您得到的是一个空列表。
如果你这样做:
x = MyClass()
inspect.getmembers(x, predicate=inspect.ismethod)
你会得到方法。
使用 inspect
列出给定 class 的所有 class 方法的 "optimal" 方法是什么?如果我像这样
getmembers
中使用 inspect.isfunction
作为谓词,它会起作用
class MyClass(object):
def __init(self, a=1):
pass
def somemethod(self, b=1):
pass
inspect.getmembers(MyClass, predicate=inspect.isfunction)
returns
[('_MyClass__init', <function __main__.MyClass.__init>),
('somemethod', <function __main__.MyClass.somemethod>)]
但是它不是应该通过 ismethod
工作吗?
inspect.getmembers(MyClass, predicate=inspect.ismethod)
在这种情况下,returns 是一个空列表。如果有人可以澄清发生了什么,那就太好了。我是 运行 这个 Python 3.5.
如文档中所述,inspect.ismethod
将显示绑定方法。这意味着如果你想检查它的方法,你必须创建一个 class 的实例。由于您正在尝试检查未实例化 class 上的方法,因此您得到的是一个空列表。
如果你这样做:
x = MyClass()
inspect.getmembers(x, predicate=inspect.ismethod)
你会得到方法。