Skip to content
Related Articles

Related Articles

Print objects of a class in Python
  • Last Updated : 29 Dec, 2019

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.

Refer to the below articles to get the idea about classes and objects in Python.

Printing objects give us information about the objects we are working with. In C++, we can do this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class. In Java, we use toString() method. In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users.

Example:




# Python program to demonstrate
# object printing
  
  
# Defining a class
class Test: 
    def __init__(self, a, b): 
        self.a =
        self.b =
      
    def __repr__(self): 
        return "Test a:% s b:% s" % (self.a, self.b) 
    
    def __str__(self): 
        return "From str method of Test: a is % s, "
              "b is % s" % (self.a, self.b) 
  
# Driver Code         
t = Test(1234, 5678
  
# This calls __str__() 
print(t) 
  
# This calls __repr__() 
print([t])

Output:



From str method of Test: a is 1234, b is 5678
[Test a:1234 b:5678]

Important Points about Printing:

  • Python uses __repr__ method if there is no __str__ method.

    Example:




    class Test: 
        def __init__(self, a, b): 
            self.a =
            self.b =
        
        def __repr__(self): 
            return "Test a:% s b:% s" % (self.a, self.b) 
        
    # Driver Code         
    t = Test(1234, 5678
    print(t)

    Output:

    Test a:1234 b:5678
    
  • If no __repr__ method is defined then the default is used.

    Example:




    class Test: 
        def __init__(self, a, b): 
            self.a =
            self.b =
        
    # Driver Code         
    t = Test(1234, 5678
    print(t)  

    Output:

    <__main__.Test object at 0x7f9b5738c550>
    

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :