简体   繁体   English

使用Python`inscu`模块列出所有类成员

[英]Listing all class members with Python `inspect` module

What is the "optimal" way to list all class methods of a given class using inspect ? 使用inspect列出给定类的所有类方法的“最佳”方法是什么? It works if I use the inspect.isfunction as predicate in getmembers like so 如果我在这样的inspect.isfunction使用inspect.isfunction作为谓词, getmembers可以工作

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>)]

But isn't it supposed to work via ismethod ? 但它不应该通过ismethod工作吗?

 inspect.getmembers(MyClass, predicate=inspect.ismethod)

which returns an empty list in this case. 在这种情况下返回一个空列表。 Would be nice if someone could clarify what's going on. 如果有人能澄清正在发生的事情会很好。 I was running this in Python 3.5. 我在Python 3.5中运行它。

As described in the documentation, inspect.ismethod will show bound methods. 如文档中所述, inspect.ismethod将显示绑定方法。 This means you have to create an instance of the class if you want to inspect its methods. 这意味着如果要检查其方法,则必须创建该类的实例。 Since you are trying to inspect methods on the un-instantiated class you are getting an empty list. 由于您正在尝试检查未实例化的类上的方法,因此您将获得一个空列表。

If you do: 如果你这样做:

x = MyClass()
inspect.getmembers(x, predicate=inspect.ismethod)

you would get the methods. 你会得到方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM