How to Display All Attributes of a Class or an Instance of a Class in Python


In this article, we show how to display all attributes of a class or an instance of a class in Python.

You may create a class and then an instance of the class. You may want to check all of the attributes of that class or an instance of the class.

So, if we create a class with an __init__ method that accepts 4 parameters and don't create any additional instance variables, the instance will be composed of these 4 parameters. We can then display all of these parameters with the __dict__ method.

If we add in class variables to the class, then we can show these in the same way with the __dict__ method.

The best way to understand this is to see an example.

So let's say we create a class named Car and define an __init__ method that accepts the parameters, type, year, color, and number_of_doors. And then we create an instance of this Car class named Car1.

We then can print out all of the attributes of this Car1 class to see what attributes it contains and what values these variables are assigned it using the __dict__ method.

So the following code below shows how to do this.

So you can see using the __dict__ method, we can get a list of all attributes, along with their values presented to us.

So this can be a very useful debugging method when you are create an object and maybe add attributes to it and want to see where you are in the process. The __dict__ method will show all attributes and attribute values.

You also use this for a class as well.

If we run the __dict__ method on the Car class, we get the following output, shown below.

A class, however, has much more built-in attributes, so many of the things you see in the dictionary of a class, you may not necessarily be interested in. This method, though, will reveal all attributes (or variables of the class).

So, let's say, we create a variable of the class Car named engine="6 cylinder"

And then run the __dict__ method, we get the following output.

Now you can see this attribute of the class displayed with the __dict__ method.

So the __dict__ method is a very useful method in Python to display all attributes of an instance of a class or other data type such as a class itself.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...