Python print object attributes | Example code

Use dir() or vars() inspect module to get object attributes and then print it using the print() method.

Python print object attributes example

Simple example code.

Using the dir() Function in Python

Call dir() function without arguments, returns the list of the names in the current local scope, and with argument, it returns the list of the object’s valid attributes

To use pprint funciton you have to import this module.

from pprint import pprint

my_list = list()



Python print object attributes

Using the vars() Function in Python

Calling vars() function without arguments, returns the dictionary with the current local symbol table. And with arguments, 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.

from pprint import pprint


Another example

class MyObj(object):
    def __init__(self): = 'Chuck Norris' = '+6661'

obj = MyObj()


{'name': 'Chuck Norris', 'phone': '+6661'}
['__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__', 'name', 'phone']

Do comment if you have any doubts and suggestions on this Python Object topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.