How to Print Object’s Attributes in Python

Knowing how to print object attributes in Python is a valuable skill for any programmer. It can help you understand how objects are constructed and manipulated in Python and how to access and use their attributes. One of the most valuable features of Python is the ability to print an object’s attributes. This page demonstrates how to print an object’s attributes in Python, including using the built-in dir() and vars() functions. This can be useful for debugging and understanding an object’s properties. This page will cover various examples of how a code example can accomplish this.

By keeping in mind, the limitations of Python syntax to print the object attributes when working with the __dir__() and dir() methods, the dir() produces a sorted list by comparing the data type of object attributes.

Some of the common methods to print the Object’s attribute in python are:

  •  __dict__ function to print Object’s attributes in Python
  • getattr() method to print Object’s Attributes in Python
  • __getattribute__ function to print object attributes in Python. 
  • Print Object’s Attributes in Python using inspect module in aggregation with getmembers() function
  • Print Object’s Attributes in Python using vars()
  • Print Object’s Attributes in Python using __dir__() and  dir() method (__dir__() vs  dir() method)
  • Print Object’s Attributes in Python using the dir() method without passing an argument
  • Print Object’s Attributes in Python using the __dir__() method without passing an argument
  • Handling Nested classes to print Print Object’s Attributes in Python

*working on Jupyter Notebook Anaconda Environment Python version 3+. 

Object attributes are the characteristics of an object. For instance, if an object is a human its attributes are complexion, height, gender, and many more. In contrast to an attribute, an object is a real-world entity, while an attribute is it’s characteristic. here are the following methods to print the attributes of the object in Python. 

__dict__ function to print Object’s attributes in Python

Any object’s attributes and its values can be retrieved using the __dict__ function. Moreover, All attribute values of the object associated with an instance are stored as a dictionary in the __dict__ attribute. 

Here’s how it executes:

  • Creating a class defines the class name as “www.” 
  • The class’s constructor (__init__) will create a variable named “name”.
  • In the final step, we will initialize the class variable url (an object) and pass the class instance ‘com’ value. 
  • Print the object attribute using (.) operator by using the class object with the instance. 

Now invoke the  __dict__ attribute with the object using the (.) operator and print the Object attribute, for instance, “name”. The output will return in dictionary data type.

class www(object):
   def __init__(self, name):
       self.name = name
url=www('com')
print("class object attribute :", url.name)
print('\n')
# invoking the __dict__ attribute
print(url.__dict__)
class object attribute : com


{'name': 'com'}

getattr() method to print an Object’s Attributes in Python

Object attributes are obtained with Python’s getattr() function. However, It returns the default value if no attribute for the object is found when using the Python getattr() function. Here’s how the getattr() method helps to print the Object’s attributes in Python. 

  • Defining a class having the name ‘website’. 
  • Define a class constructor __init__ () and pass an instance for the object as a parameter to it.  constructor __init__ () is created whenever there is a need to access the class object attributes.
  •  Now create an object “url”. 
  • Invoke a getattr() and pass two arguments in it, the first is the created object, and the second is the object attribute contains some instance value. 
  • However, this will print the attributes of the object in a few simple steps.
class website:
   def __init__(self, url):
       self.url = url
url = website("www.entechin.com")
# get attribute values by using getattr() function
print('\ngetattr : url of website is =', getattr(url, "url"))
getattr : url of website is = www.entechin.com

__getattribute__ function to print object attributes in Python. 

When there is a need to access the object attributes, __getattribute__ function, however, invokes within classes. 

Here’s how it executes:

  • Creating a class with the name “website”.
  • Now invoke __getattribute__ as a defined function within a class. 
  • Define an object “url_path”.
  • Using url_path and url using (.) dot operator to get at the object attributes.
  • Now return the url_path with url(attribute name) to print the object’s attributes using the (.) operator.
class website(object):
    def __getattribute__(self, url):
       return object.__getattribute__(self, url)
url_path = website()
url_path.url = 'www.entechin.com'
url_path.url
'www.entechin.com'

Print Object’s Attributes in Python using inspect module in aggregation with getmembers() function

Object attributes in Python can be accessed in a Python program using inspect module in aggregation with getmembers() function with the help of the dot(.) operator. However, the program returns the attributes in a dictionary data type. 

Here’s how it executes:

  • Import pprint module for better readability and understanding of output that has computationally expensive content containing difficult data structure.
  • Now import inspect module.
  • Using Python’s inspect module, you can inspect code modules and objects. However, It returns content about classes, methods, functions, etc. Moreover, it is beneficial in producing information about class objects and their object attributes.
  • However, to print all the attributes of the Object in Python, getmembers() gives us a convenient way to access all the attributes of the Object. 
  • Moreover, dot(.) operators allow us to use getmembers() with inspect module. 
  • However, the output of these functions returns the list of tuples containing information about the class attributes with their defined values.
  • Creating a class defines the class name as “flowers”. 
  • The class’s constructor (__init__) will create a variable named flower1, flower2, flower3.
  • Moreover, “self” is a class object within the class’s constructor (__init__). 
  • In the final step, we will initialize the class variable “class_object” (an object) and pass the value of the class instance ‘Red Ginger’,’Tree Poppy’,’passion flower’. 
  • Print the object attribute using the (.) operator by using the class object with the instance. 
  • Now invoke the inspect module in aggregation with getmembers() function using the (.) operator and print the Object attribute, for instance, “flower1, flower2, flower3”. However, The output will return in dictionary and tuple data type with values of the object attributes.
# print out all attributes of an object in Python
#import pprint module for readability
from pprint import pprint
# importing inspect module from the path
import inspect
# considering a class of unique name
class flowers:
   # class variable
   class_variable = 1
   def __init__(self, flower1, flower2, flower3):
       
# self is itself a class object, define within a  __init__ contructor method
#flower1, flower2, flower3 varibles attributes in instance or instance attributes as belong to the class flowers
           self.flower1 = flower1
           self.flower2 = flower2
           self.flower3 = flower3
# creating a class object for variable attributes
class_object = flowers('Red Ginger','Tree Poppy','passion flower')
# calling getmembers() function of the inspect module using (.) operator
# passing class object "class_object" as parameter
pprint(inspect.getmembers(class_object))
[('__class__', <class '__main__.flowers'>),
 ('__delattr__',
  <method-wrapper '__delattr__' of flowers object at 0x000001FDCB64E880>),
 ('__dict__',
  {'flower1': 'Red Ginger',
   'flower2': 'Tree Poppy',
   'flower3': 'passion flower'}),
 ('__dir__', <built-in method __dir__ of flowers object at 0x000001FDCB64E880>),
 ('__doc__', None),
 ('__eq__', <method-wrapper '__eq__' of flowers object at 0x000001FDCB64E880>),
 ('__format__',
  <built-in method __format__ of flowers object at 0x000001FDCB64E880>),
 ('__ge__', <method-wrapper '__ge__' of flowers object at 0x000001FDCB64E880>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of flowers object at 0x000001FDCB64E880>),
 ('__gt__', <method-wrapper '__gt__' of flowers object at 0x000001FDCB64E880>),
 ('__hash__',
  <method-wrapper '__hash__' of flowers object at 0x000001FDCB64E880>),
 ('__init__',
  <bound method flowers.__init__ of <__main__.flowers object at 0x000001FDCB64E880>>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x000001FDCA3A0AF0>),
 ('__le__', <method-wrapper '__le__' of flowers object at 0x000001FDCB64E880>),
 ('__lt__', <method-wrapper '__lt__' of flowers object at 0x000001FDCB64E880>),
 ('__module__', '__main__'),
 ('__ne__', <method-wrapper '__ne__' of flowers object at 0x000001FDCB64E880>),
 ('__new__', <built-in method __new__ of type object at 0x00007FFB933C3E00>),
 ('__reduce__',
  <built-in method __reduce__ of flowers object at 0x000001FDCB64E880>),
 ('__reduce_ex__',
  <built-in method __reduce_ex__ of flowers object at 0x000001FDCB64E880>),
 ('__repr__',
  <method-wrapper '__repr__' of flowers object at 0x000001FDCB64E880>),
 ('__setattr__',
  <method-wrapper '__setattr__' of flowers object at 0x000001FDCB64E880>),
 ('__sizeof__',
  <built-in method __sizeof__ of flowers object at 0x000001FDCB64E880>),
 ('__str__',
  <method-wrapper '__str__' of flowers object at 0x000001FDCB64E880>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x000001FDCA3A0AF0>),
 ('__weakref__', None),
 ('class_variable', 1),
 ('flower1', 'Red Ginger'),
 ('flower2', 'Tree Poppy'),
 ('flower3', 'passion flower')]

Print Object’s Attributes in Python using vars()

Vars allows us to access the object attributes in Python using the vars() function in Python. However, vars() is an in-built function and allows taking the object as a parameter or class, method, or instance that possesses dictionary attributes. Moreover, By default, It returns all object attributes when no parameter is passed. 

It returns the output (object attributes) in key-value dictionary format. 

The syntax of the vars() function is:

pprint(vars(class_object))

Where 

Class_object – as a passing object as a parameter to vars() function

pprint – pprint() is similar to print() to enhance the exposure of readability, and to pretty print the object attributes in Python. Moreover, pprint is used to display complex data structures.

Here is how it executes!

  • Importing the pprint module to pretty print the object
  • Creating the class of a flower
  • Defining a constructor __init__(self, flower1, flower2, flower3), having an instance (class object) self, and other instance attributes.
  • Creating a class object and passing attributes as parameters to the class.
  • Now printing the object attributes in Python. 
  • The output of object attributes will return in dictionary format containing keys and their values.
  • Keys will be the instances variables initialized in the constructor, and values are the attributes passed as parameters to the class objects. 
# import pprint module
from pprint import pprint
class flowers():
   # class variable
   class_variable = 1
 # class constructor defining
   def __init__(self, flower1, flower2, flower3):
#flower1, flower2, flower3 varibles attributes in instance or instance attributes as belong to the class flowers
           self.flower1 = flower1
           self.flower2 = flower2
           self.flower3 = flower3
 # class object creating
class_object= flowers('Red Ginger','Tree Poppy','passion flower')
# calling the vars() function
pprint(vars(class_object))
{'flower1': 'Red Ginger', 'flower2': 'Tree Poppy', 'flower3': 'passion flower'}

Print Object’s Attributes in Python using __dir__() and  dir() method (__dir__() vs  dir() method)

__dir__() and dir() methods are another approach to accessing an object’s attributes in Python. 

In addition, It is interesting to compare the outputs returned by dir() and __dir__(). In contrast to the __dir__() method, the dir() function returns an attribute list sorted (ordered) by the specified object attribute. 

where

 __dir__() method returns object attributes as it is, whether it contains a dictionary, tuple, set, or a list containing strings or a number.

However, it is necessary to keep in mind that the dir() method has some limitations in Python. Additionally, When object attributes are of string type, it will return output as a List. However, if object attributes consist of characters or numbers, it returns the TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

In the following example  __dir__() method is defined within a class. 

However, Here is the following example that executes the whole process:

from pprint import pprint

class flowers():
    # create a function of the __dir__() method 
    def __dir__(self):
        return {'Red Ginger','Tree Poppy','passion flower'}

 # class variable
    class_variable = 1

# creating object
class_object= flowers()

# calling the __dir__() method
print("using __dir__() method object attributes is: ", class_object.__dir__())
# calling the dir() method
print("The dir() method returns: ", dir(class_object))
using __dir__() method object attributes is:  {'passion flower', 'Red Ginger', 'Tree Poppy'}
The dir() method returns:  ['Red Ginger', 'Tree Poppy', 'passion flower']

Here change the example scenario as:

Printing a string with an integer number invokes a type error. Dir() produces a sorted list by comparing the type of object attributes. However, since the data-types string (‘Red Ginger’, ‘Tree Poppy’, ‘passion flower) and integer (1) are incomparable. Therefore, The dir() method cannot be called on this object; therefore, an error results.

from pprint import pprint

class flowers():
    # create a function of the __dir__() method 
    def __dir__(self):
        return {'Red Ginger','Tree Poppy','passion flower',1}

 # class variable
    class_variable = 1

# creating object
class_object= flowers()

# calling the __dir__() method
print("using __dir__() method object attributes is: ", class_object.__dir__())
# calling the dir() method
print("The dir() method returns: ", dir(class_object))
using __dir__() method object attributes is:  {'passion flower', 'Red Ginger', 1, 'Tree Poppy'}
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7728/2891281098.py in <module>
     15 print("using __dir__() method object attributes is: ", class_object.__dir__())
     16 # calling the dir() method
---> 17 print("The dir() method returns: ", dir(class_object))

TypeError: '<' not supported between instances of 'int' and 'str'

Printing Object’s Attributes in Python using the dir() method without passing an argument

Python provides an inbuilt function dir()  that lists all an object’s attributes. Moreover, With this function, you can retrieve all the attributes (class, methods, or objects) that belongs to the passing parameter, or additionally, it has the option to pass no parameter to it. Moreover, in the following example, no parameter is passed to it.

Here is how it works!

  • Import pprint to pretty print object attributes
  • Define variables and save them to their objects.
  • Invoking dir() function without passing any parameter to it.
  • However, Locally defined attributes, as well as inbuilt attributes, were returned by dir().
#pretty print object attributes
from pprint import pprint
# printing all attributes of an object in Python
web = "www.entechin.com"
query = "How to print Object's attributes in Python?"
# calling dir() function without passing any parameter
print(dir())
['In', 'Out', 'Student', '_', '_3', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15', '_i16', '_i17', '_i18', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'class_object', 'exit', 'flowers', 'flowers_names', 'get_ipython', 'j', 'm', 'pprint', 'query', 'quit', 's', 'web']

Printing Object’s Attributes in Python using  __dir__() method without passing an argument

Keeping in mind that __dir__() method without passing a parameter, however, returns a priority ranking in the list returned by the method based on the attributes defined by the user.

As shown in the output [‘flower1’, ‘flower2’, ‘__module__’, ‘__init__’, ‘List’, ‘var’, ‘__dict__’,…..]

Where [‘flower1’, ‘flower2′,’List’] are user-defined in their local scope. 

Here is how it executes!

  • Creating a class
  • Define a constructor with instance variables.
  • Define a function List by passing an inbuilt class object “self” to its scope
  • The List function replaces the instance with the corresponding object attributes and returns the string formatted in an f-string structure. However, instance variables update their value when the class is called. In the next step, the class is called an object attributes are passed to it. 
  • Now invoke the class and pass the instance variables attributes to it. And save it to an object name class_object.
  • Now print the object attributes.
class flowers():
    def __init__(self, flower1, flower2):
            self.flower1 = flower1
            self.flower2 = flower2
            
    def List(self):
        return f'flower 1: {self.flower1} and flower 2: {self.flower2}'

    # class variable
    var = 1

# creating object
class_object = flowers('Red Ginger','Tree Poppy')
print(class_object.List())
print(class_object.__dir__())
flower 1: Red Ginger and flower 2: Tree Poppy
['flower1', 'flower2', '__module__', '__init__', 'List', 'var', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']

Handling Nested classes for Printing Object’s Attributes in Python

The dir() function is a built-in function in Python that provide accessibility to print the objects attributes of a nested class. 

However, To print the nested class attributes, vars() function helps to perform the task. 

Moreover, dir() function, If no parameters are passed to the dir() method it returns all attributes that users used in their local Python code shell.

Here’s how it executes:

  • Defining a nested classes 
  • Define the contractor for both classes individually and pass instance variables to both the constructors. 
  • super () function in Python returns a objects that belongs to the parents class or exist in parent class.
  • Now create an object for both classes respectively, and pass objects attributes to the class() as parameter.
  • Print the Object attributes with vars() function using print command, and it will returns the object attributes in key-value format. 
  • dir() function returns all the object attributes. 
class flowers():
    def __init__(self, flower1, flower2, flower3):
            self.flower1 = flower1
            self.flower2 = flower2
            self.flower3 = flower3

class flowers_names(flowers):
      def __init__(self,  flower1, flower2, flower3,flower4):
            super().__init__(flower1, flower2, flower3)
            self.flower4 = flower4

m= flowers('Red Ginger','Tree Poppy','passion flower')
j= flowers_names('Red Ginger','Tree Poppy','passion flower','water lily')

print("vars(m):", vars(m))
print("vars(j):", vars(j))

dir(m)

vars(m): {'flower1': 'Red Ginger', 'flower2': 'Tree Poppy', 'flower3': 'passion flower'}
vars(j): {'flower1': 'Red Ginger', 'flower2': 'Tree Poppy', 'flower3': 'passion flower', 'flower4': 'water lily'}
 
 
['__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__',
 'flower1',
 'flower2',
 'flower3']

Conclusion

Print object attributes are a computationally expensive task to be accomplished. However, using the class, three different approaches are demonstrated on this page to pretty print the Object’s attributes in Python. These methods include __getattribute__(), getattr(), and  __dict__(), inspect module, vars(), dir() method, __dir__() method, and dir() method, __dir__() method without passing any parameter to it to accomplish this task. 

If you want to learn more about Python Programming, Visit Python Programming Tutorials.

Leave a Comment

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