Python print object of Class | Example code

Use anyone from the repr() Method or Using the str() Method or Adding New Class Method to print object in Python. A class is like a blueprint while an object is a copy of the class with actual values.

Python print object example

Simple example code.

Using the repr() Method

Python uses __repr__ a method if there is no __str__ method. It returns the object’s printable representation in the form of a string. It, by default, returns the name of the object’s class and the address of the object.

class Hello():
    def __init__(self):
        self.var1 = 0
        self.var2 = "Hello"

    def __repr__(self):
        return "This is object of class Hello"


A = Hello()
print(A)

Output:

Python print object of Class

If no __repr__ method is defined then the default is used.

class Hello():
    def __init__(self):
        self.var1 = 0
        self.var2 = "Hello"


A = Hello()
print(A)

Output: <main.Hello object at 0x000002EC327C2308>

Using the str() Method

The str() method returns the string version of the object in Python. If an object does not have an str() method, it returns the same value as the repr() method.

class Hello():
    def __init__(self):
        self.var1 = 0
        self.var2 = "Hello"

    def __repr__(self):
        return "This is object of class Hello"

    def __str__(self):
        print("var1 =", self.var1)
        print("var2 =", end=" ")
        return self.var2


A = Hello()
print(A)

Output:

var1 = 0
var2 = Hello

Do comment if you have any doubts and suggestions on this Python object topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.