• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Print Object Attributes in Python using dir() Function

Print Object Attributes in Python using dir() Function

March 5, 2022 Leave a Comment

To print an object’s attributes using Python, the easiest way is with the dir() function.

list_object = [1, 2, 3]

print(dir(list_object))

#Output:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

To get all of the attributes of an object via the class, you can use vars() or __dict__ to print attributes of an object.

import pprint 

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

pprint.pprint(vars(Person))
pprint.pprint(Person.__dict__)

#Output:
{'__dict__': <attribute '__dict__' of 'Person' objects>,
              '__doc__': None,
              '__init__': <function Person.__init__ at 0x000002B3AD09E430>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Person' objects>}
{'__dict__': <attribute '__dict__' of 'Person' objects>,
              '__doc__': None,
              '__init__': <function Person.__init__ at 0x000002B3AD09E430>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Person' objects>}

When working with objects in Python, it is useful to be able to see all of the attributes of an object.

We can easily print the attributes of objects in Python with the dir() function.

Below is a simple example of getting and printing the attributes of a list object in Python with dir().

list_object = [1, 2, 3]

print(dir(list_object))

#Output:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Printing Object Class Attributes with vars() Function in Python

If you are working with classes and want to list the attributes of the class, then you can use the vars() function.

The vars() function return the ‘__dict__’ attribute from the class and will list all of the attributes.

For example, let’s say we have a class “Person” as shown below.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

To list all of the attributes of “Person”, we can pass it to vars().

Let’s also use the pprint module here to pretty print the returned dictionary of attributes.

import pprint 

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

pprint.pprint(vars(Person))
pprint.pprint(Person.__dict__)

#Output:
{'__dict__': <attribute '__dict__' of 'Person' objects>,
              '__doc__': None,
              '__init__': <function Person.__init__ at 0x000002B3AD09E430>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Person' objects>}
{'__dict__': <attribute '__dict__' of 'Person' objects>,
              '__doc__': None,
              '__init__': <function Person.__init__ at 0x000002B3AD09E430>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Person' objects>}

Example of Using vars() to Print List Class Attributes in Python

Here, I’d like to show an example of how to print the class attributes of the list class in Python. Lists are one of the most commonly used objects in Python.

To print all of the class attributes of the class list, we pass ‘list’ to vars().

Below is an example in Python of how to use vars() to print attributes of the class ‘list’.

import pprint 

pprint.pprint(vars(list))

{'__add__': <slot wrapper '__add__' of 'list' objects>,
              '__class_getitem__': <method '__class_getitem__' of 'list' objects>,
              '__contains__': <slot wrapper '__contains__' of 'list' objects>,
              '__delitem__': <slot wrapper '__delitem__' of 'list' objects>,
              '__doc__': 'Built-in mutable sequence.\n'
                         '\n'
                         'If no argument is given, the constructor creates a '
                         'new empty list.\n'
                         'The argument must be an iterable if specified.',
              '__eq__': <slot wrapper '__eq__' of 'list' objects>,
              '__ge__': <slot wrapper '__ge__' of 'list' objects>,
              '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>,
              '__getitem__': <method '__getitem__' of 'list' objects>,
              '__gt__': <slot wrapper '__gt__' of 'list' objects>,
              '__hash__': None,
              '__iadd__': <slot wrapper '__iadd__' of 'list' objects>,
              '__imul__': <slot wrapper '__imul__' of 'list' objects>,
              '__init__': <slot wrapper '__init__' of 'list' objects>,
              '__iter__': <slot wrapper '__iter__' of 'list' objects>,
              '__le__': <slot wrapper '__le__' of 'list' objects>,
              '__len__': <slot wrapper '__len__' of 'list' objects>,
              '__lt__': <slot wrapper '__lt__' of 'list' objects>,
              '__mul__': <slot wrapper '__mul__' of 'list' objects>,
              '__ne__': <slot wrapper '__ne__' of 'list' objects>,
              '__new__': <built-in method __new__ of type object at 0x00007FFBC24E0AF0>,
              '__repr__': <slot wrapper '__repr__' of 'list' objects>,
              '__reversed__': <method '__reversed__' of 'list' objects>,
              '__rmul__': <slot wrapper '__rmul__' of 'list' objects>,
              '__setitem__': <slot wrapper '__setitem__' of 'list' objects>,
              '__sizeof__': <method '__sizeof__' of 'list' objects>,
              'append': <method 'append' of 'list' objects>,
              'clear': <method 'clear' of 'list' objects>,
              'copy': <method 'copy' of 'list' objects>,
              'count': <method 'count' of 'list' objects>,
              'extend': <method 'extend' of 'list' objects>,
              'index': <method 'index' of 'list' objects>,
              'insert': <method 'insert' of 'list' objects>,
              'pop': <method 'pop' of 'list' objects>,
              'remove': <method 'remove' of 'list' objects>,
              'reverse': <method 'reverse' of 'list' objects>,
              'sort': <method 'sort' of 'list' objects>}

Hopefully this article has been helpful for you to learn how to print object attributes using Python.

Other Articles You'll Also Like:

  • 1.  How to Get the Size of a List in Python Using len() Function
  • 2.  Using if in Python Lambda Expression
  • 3.  Python acos – Find Arccosine and Inverse Cosine of Number
  • 4.  numpy pi – Get Value of pi Using numpy Module in Python
  • 5.  Python sin – Find Sine of Number in Radians Using math.sin()
  • 6.  Check if a Number is Divisible by 2 in Python
  • 7.  Drop First n Rows of pandas DataFrame
  • 8.  Using Python to Convert Timestamp to Date
  • 9.  Get First Key and Value in Dictionary with Python
  • 10.  Using Python to Compare Strings Alphabetically

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy

x