Print Object's Attributes in Python

  1. Print Attributes of an Object in Python Using the dir() Function in Python
  2. Print Attributes of an Object in Python Using the vars() Function in Python

This tutorial will explain various methods to print the attributes of an object in Python. An attribute in object-oriented programming is the property of a class or an instance. For example, a class named student can have name, roll no and marks, etc as its attributes. Every instance of the class shares all the attributes of a class.

In this tutorial, we will look into how to get and print an object’s attributes in Python.

The built-in dir() function, when called without arguments, returns the list of the names in the current local scope, and when an object is passed as the argument, it returns the list of the object’s valid attributes.

To print the object’s attributes, we need to pass the object to the dir() function and print the object’s attributes returned by the dir() object. We can use the pprint() method of the pprint module to print the attributes in a well-formatted way. The below example code demonstrates how to use the dir() function to print the attributes of the object:

from pprint import pprint

mylist = list()
pprint(dir(mylist))

Output:

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 ...
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 ...
 'remove',
 'reverse',
 'sort']

The vars() functions, when called without arguments, returns the dictionary with the current local symbol table. If an object is passed to the vars() function, it returns the __dict__ attribute of the object. If the object provided as input does not have the __dict__ attribute, a TypeError will be raised.

The below code example demonstrates how to use the vars() function to print an object’s attributes in Python.

from pprint import pprint

pprint(vars(myobject))
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.