简体   繁体   中英

Listing all class members with Python `inspect` module

What is the "optimal" way to list all class methods of a given class using inspect ? It works if I use the inspect.isfunction as predicate in getmembers like so

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 ?

 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.

As described in the documentation, inspect.ismethod will show bound methods. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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