Print Methods of Object in Python
Working with Python methods and attributes is very easy but seems challenging when we want to know if a specific object has a particular method/attribute or not.
This tutorial teaches the use of dir() , and inspect.getmembers() to print all methods of a Python object. We will also learn how to filter magic methods and check if an attribute is callable or not.
Finally, we will learn hasattr() and getattr() to find a specific attribute of a Python object and its value.
Use dir() to Print All Methods of Python Object
The dir() is a built-in Python function which returns all the attributes and methods (without values) of a specified object. It not only returns the built-in attributes (also known as properties) and methods but we can also get user-defined properties and methods.
To use the built-in dir() method, let’s create a string-type object and name it first_name which will contain a string-type value. Next, we use the dir() method, pass it first_name object, and save the returned output by the dir() method in a new variable, called result .
Finally, we print the values of result to get a list of all the methods and attributes of a Python object, which is first_name here.
[ ‘__add__’ , ‘__class__’ , ‘__contains__’ , ‘__delattr__’ , ‘__dir__’ , ‘__doc__’ , ‘__eq__’ , ‘__format__’ , ‘__ge__’ , ‘__getattribute__’ , ‘__getitem__’ , ‘__getnewargs__’ , ‘__gt__’ , ‘__hash__’ , ‘__init__’ , ‘__init_subclass__’ , ‘__iter__’ , ‘__le__’ , ‘__len__’ , ‘__lt__’ , ‘__mod__’ , ‘__mul__’ , ‘__ne__’ , ‘__new__’ , ‘__reduce__’ , ‘__reduce_ex__’ , ‘__repr__’ , ‘__rmod__’ , ‘__rmul__’ , ‘__setattr__’ , ‘__sizeof__’ , ‘__str__’ , ‘__subclasshook__’ , ‘capitalize’ , ‘casefold’ , ‘center’ , ‘count’ , ‘encode’ , ‘endswith’ , ‘expandtabs’ , ‘find’ , ‘format’ , ‘format_map’ , ‘index’ , ‘isalnum’ , ‘isalpha’ , ‘isascii’ , ‘isdecimal’ , ‘isdigit’ , ‘isidentifier’ , ‘islower’ , ‘isnumeric’ , ‘isprintable’ , ‘isspace’ , ‘istitle’ , ‘isupper’ , ‘join’ , ‘ljust’ , ‘lower’ , ‘lstrip’ , ‘maketrans’ , ‘partition’ , ‘removeprefix’ , ‘removesuffix’ , ‘replace’ , ‘rfind’ , ‘rindex’ , ‘rjust’ , ‘rpartition’ , ‘rsplit’ , ‘rstrip’ , ‘split’ , ‘splitlines’ , ‘startswith’ , ‘strip’ , ‘swapcase’ , ‘title’ , ‘translate’ , ‘upper’ , ‘zfill’ ]Here, we have retrieved all the attributes and methods, the methods starting and ending with double underscores ( __ ) are called dunder methods or magic methods , which are called by the wrapper functions .
It means dunder or magic methods are not directly invoked by us (the programmers) but their invocation occurs internally from a specific class based on a particular action.
For instance, if we call the dir() method then __dict__() would be invoked behind the scenes. Let’s take another example, where we add two numbers using the + operator, internally, the __add__() method would be called to perform this operation.
As we are not using the magic methods directly so, we can filter them and get a list of methods and attributes that we can directly use from our code. So, let’s dive into the following section to learn how to filter magic methods .
Filter Magic Methods
Here, we use a for loop to iterate over a list returned by dir(first_name) (you can replace first_name with your object) and if statement to filter out magic or dunder methods, we wrap this code with square brackets ( [] ) to get a list type output.
List All the Methods of a Python Module
- List All the Methods of a Python Module Using the dir() Method
- List All the Methods of a Python Module Using the inspect() Module
A Python module, package, or library is a file or group of files containing definitions of Python functions, Python classes, and Python variables. In Python, we can import a module and use its implementations to stick with two important concepts of the world of computer science; Don’t reinvent the wheel and Don’t repeat yourself .
These packages or modules can be as small as a few lines and as big as millions of lines. As the size grows, it becomes difficult to analyze modules or see a clear outline of the content of the package. But Python developers have solved that problem for us as well.
In Python, there are many ways in which we can list down methods and classes of a Python module. In this article, we will talk about two such practices with the help of relevant examples. Note that, for instance, we will consider the NumPy Python module. If you don’t have the NumPy package on your system or virtual environment, you can download it using either the pip install numpy or the pip3 install numpy command.
List All the Methods of a Python Module Using the dir() Method
The dir() method is an in-built method in Python. It prints all the attributes and methods of an object or a Python package. Check the following code to understand it.
class A: a = 10 b = 20 c = 200 def __init__(self, x): self.x = x def get_current_x(self): return self.x def set_x(self, x): self.x = x def __repr__(self): return f"X: x>" print(dir(int)) print(dir(float)) print(dir(A))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] ['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real'] ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c', 'get_current_x', 'set_x']
We can use the dir() method to list down all the module methods. Refer to the following code to see how.
import numpy print("NumPy Module") print(dir(numpy))
As we can see, the dir() method has listed all the NumPy methods.
List All the Methods of a Python Module Using the inspect() Module
The inspect module is a Python module that has several helpful functions to get useful information about modules, classes, class objects, functions, tracebacks, and objects. We can use this module for our simple purpose. Refer to the following code to learn about its usage.
import numpy from inspect import getmembers, isfunction print("NumPy Module") print(getmembers(numpy, isfunction))
- ismodule() : Return True if the object is a module.
- isclass() : Return True if the object is a class.
- istraceback() : Return True if the object is a traceback.
- isgenerator() : Return True if the object is a generator.
- iscode() : Return True if the object is a code.
- isframe() : Return True if the object is a frame.
- isabstract() : Return True if the object is an abstract base class.
- iscoroutine() : Return True if the object is a coroutine.
To learn more about this module, refer to the official documentation.
Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.