Print Methods of Object in Python

💡 TL;DR

To get all methods of object, use inbuilt dir() method

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.

Example Code:

OUTPUT:

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.

Example Code:

OUTPUT:

Now, we have all those attributes and functions that we can use directly from our code. For instance, we can use upper and count with () as follows:

OUTPUT:

One worth noting point is, how we know whether we have to write () or not because we have filtered magic methods only and still have some attributes that might not be callable. For that, we can use callable() and pass it to the object that we want to check.

Use callable() to Check if an Object is Callable or Not

If callable() returns True then, the specified object is callable and we can use () with it. On the other hand, if callable() returns False then, the specified object is not callable and we don’t need to use ().

In simple words, we can say that () are used with methods/functions, not with attributes/properties. See the following code to understand it.

Example Code:

OUTPUT:

The above output shows that we can use () with first_name_object only. Let’s test it by using the following print statements.

The first print statement returns the desired value Mehvish which proves that the first_name_object is callable and allows us to use () while the second print statement generates TypeError saying that it is not callable so, we can’t use ().

It means we can only use () with functions/methods, not with attributes/properties. So, there might be a chance that we also want to filter attributes/properties. Let’s explore it in the following section.

Filter All Attributes/Properties that Are Not Callable

Let’s create a Person class to learn how to filter all attributes/properties that are not callable. This Person class has four attributes and a method which are briefly explained below:

  1. first_name – This attribute contains the first name of a person.
  2. last_name – This attribute contains the last name of a person.
  3. age – This attribute contains the age of a person.
  4. call_display_information – This attribute holds a reference to a method which is defined as display_information().
  5. display_information() – This method returns a list of first_name, last_name, and age of a person.

Example Code:

Now, use the following code to filter all attributes which are not callable and magic or dunder methods as we will not be using them.

OUTPUT:

See, we only get the methods of the objects which we are looking for.

Note: The dir() method can be used on any type of Python object, it can be of string type, integer type, or user-defined type (for example, Student).

Use the inspect Module to Print All Methods of Python Object

The inspect module has various useful functions but we are focused on getmembers(), it returns all members of a specified object as a list containing (name, value) pairs, which are sorted by name.

Example Code:

OUTPUT:

Here, we have used ... to make the above output more readable but you’ll have multiple (name, value) pairs. We can also filter magic methods and check if an object is callable or not as we did while using the dir() method.

Till this point, we have learned how to list all methods/attributes of a Python object but what if we want to know about a specific attribute or a method?

For example, we have a class Student and we want to check if the Student class has a first_name attribute or a display_information() method. Let’s dive into the following section to learn it in detail.

Use getattr() & hasattr() to Print a Specific Method of a Python Object

Let’s create a Student class to use the getattr() and hasattr() methods. The following Student class has three attributes (first_name, last_name, and age) and a method (display_information()).

Example Code:

Next, create an object of the Student class as follows:

Now, we can use the hasattr() method to check if the student object has the specified attributes/methods.

To use hasattr(), we pass the object name and property name as the first parameter and second parameter respectively. See the following code fence:

OUTPUT:

The hasattr() returns True if an object has the specified attribute or method; otherwise, False.

We can also use the getattr() method similarly but it returns the value of the specified attribute or method as follows. Note that, we will get an AttributeError error if we will try to get the value of an attribute which is not defined.

OUTPUT:

Note that, we can use the type(object_name) and id(object_name) methods to get the data type and unique id of the specified object, don’t forget to replace object_name with your object_name.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *