Printing the attributes of an object in Python

vars

The vars() function simply returns the __dict__ attribute for any object that has one. Modules and user-defined class objects have a __dict__ attribute, but many other kinds of objects don’t.

dir()

The dir() function will call the object’s __dir__() if present. This will call the object’s __getattr__() or getattribute__() functions. If __dir__ is not present, dir() will try to read the object’s __dict__ attribute.

import pprint

def main():
    parrot = Parrot('Norewegian Blue', 'sleeping')
    pp = pprint.PrettyPrinter()
    print("vars()")
    pp.pprint(vars(parrot))
    print("dir()")
    pp.pprint(dir(parrot))

class Parrot(object):
    def __init__(self, breed, condition):
        self.breed = breed
        self.condition = condition


if __name__ == '__main__':
    main()
vars()
{'breed': 'Norewegian Blue', 'condition': 'sleeping'}
dir()
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'breed',
 'condition']