Skip to content

Python print object attributes | Example code

  • by

Use the 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 function you have to import this module.

from pprint import pprint

my_list = list()



Python print object attributes

Using the vars() Function in Python

Calling the 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 or suggestions on this Python Object topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

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