Sometimes, we want to get list of methods in a Python class.
In this article, we’ll look at how to get list of methods in a Python class.
How to get list of methods in a Python class?
To get list of methods in a Python class, we can use list comprehension with the dir
and callable
functions.
For instance, we write
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
to call dir
with the Foo
class to get a list of members of Foo
.
And then we use if callable(getattr(Foo, func)
to check if the func
member in the Foo
class is a function.
If it is, then we include it in the list. Otherwise, they’re filtered out.
Then a list of methods in Foo
is returned.
Conclusion
To get list of methods in a Python class, we can use list comprehension with the dir
and callable
functions.