Print objects of a class in Python

An object is the part of Object Oriented Programming (OOP), which is an instance of a class. The class is the blueprint or template that specifies the methods and properties of that class. When we create an object of a class, it contains all the instance methods and variables related to that particular object. By default, printing an object shows its memory address, but we can customize this behavior using special methods.

Using __str__ Method

The __str__ method provides a human-readable string representation of an object. It's automatically called when we use print() or str() on an object ?

class Person:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
        
    def __str__(self):
        return f"My name is {self.name} and I am {self.age} years old."

person1 = Person("John", 30, "male")
person2 = Person("Jane", 25, "female")

print(person1) 
print(person2)
My name is John and I am 30 years old.
My name is Jane and I am 25 years old.

Without __str__ Method

If we omit the __str__ method, Python prints the object's default representation showing its class and memory location ?

class Person:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
        
person1 = Person("John", 30, "male")
person2 = Person("Jane", 25, "female")

print(person1) 
print(person2)
<__main__.Person object at 0x0000029D0DAD7250>
<__main__.Person object at 0x0000029D0DBEF7F0>

Using __repr__ Method

The __repr__ method provides a detailed string representation primarily for developers and debugging. It should ideally return a string that could recreate the object ?

class Person:
    def __init__(self, name, state, city):
        self.name = name
        self.state = state
        self.city = city
        
    def __repr__(self):
        return f"Person('{self.name}', '{self.state}', '{self.city}')"
        
    def __str__(self):
        return f"{self.name} from {self.city}, {self.state}"

person1 = Person("John", "California", "Los Angeles")
person2 = Person("Jane", "Texas", "Houston")

print(str(person1))  # Calls __str__
print(repr(person1))  # Calls __repr__
print(person2)  # Calls __str__ by default
John from Los Angeles, California
Person('John', 'California', 'Los Angeles')
Jane from Houston, Texas

Comparison of __str__ vs __repr__

Method Purpose Target Audience Called By
__str__ Human-readable representation End users print(), str()
__repr__ Developer-friendly representation Developers repr(), interactive shell

Using Both Methods Together

When both methods are defined, __str__ takes priority for print() statements ?

class Student:
    def __init__(self, name, grade, subjects):
        self.name = name
        self.grade = grade
        self.subjects = subjects
        
    def __str__(self):
        return f"Student: {self.name}, Grade: {self.grade}"
        
    def __repr__(self):
        return f"Student('{self.name}', {self.grade}, {self.subjects})"

student = Student("Alice", 10, ["Math", "Science"])

print(student)        # Uses __str__
print(repr(student))  # Uses __repr__
Student: Alice, Grade: 10
Student('Alice', 10, ['Math', 'Science'])

Conclusion

Use __str__ for user-friendly output and __repr__ for debugging and development. Both methods make object printing more meaningful than default memory addresses.

Updated on: 2026-04-02T17:17:53+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements