List all class members with Python `inspect` module

What is the best way to list all the class methods of a given class with inspect? It works if I use inspect.isfunctionas a predicate in getmembers, for example,

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 shouldn't he work through ismethod?

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

which returns an empty list in this case. It would be nice if someone could clarify what was happening. I ran this in Python 3.5.

+4
source share
1 answer

, inspect.ismethod . , , . - , .

:

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

.

+8

Source: https://habr.com/ru/post/1612164/


All Articles