How do I get a list of methods in a Python class?
To quickly get a list of non-special methods from a Python class, you can use the inspect module as follows:
Output:
['chicken_nuggets', 'french_fries']
Class versus Instance Methods
Class and instance methods are plotted differently by inspect.getmembers(). To list instance methods, pass an instance:
For listing class methods, pass the class itself:
Heads-up from Python 3: inspect.ismethod metamorphosed!
Private and Special Methods
To find all attributes, including the private and "dunder" methods, use dir().
To exclude introspected ones, those starting with __, use list comprehension:
Static Methods, Anyone?
Static methods, just like weird cousins, behave differently. Here's how you nab 'em:
Docstring Comprehension
To understand what secretive methods do, peek into the docstring with inspect.getdoc(). It feels like unveiling secrets.
Runtime Check
While introspection smoothly handles runtime attributes, remember, it's not free. It can cause a performance hit, so don't overdo it.
Need help?
Python's interactive help system is like an info desk. Use help() and interrogate your class:
Was this article helpful?