Print Objects Of a class in Python














































Print Objects Of a class in Python



                                    Print Objects Of a class in Python

The class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.

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 detailed information for debugging while __str__ is used to print a string version for the users.
  

                                                                           EXAMPLe

# Defining a class
class Test:
def __init__(self, a, b):
self.a = a
self.b = 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]

                                         EXAMPLE

class Test:
def __repr__(self):
return "Test()"
def __str__(self):
return "member of Test"

t = Test()

print(t)

                                         OUTPUT
member of Test
The __str__ the method is what happens when you print it, and the __repr__ the method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.


If no __str__ the method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still, use __str__ for printing.


    This Article is Written by Rohit Bansal.


Comments