Python provides special methods, often called magic methods or dunder (double underscore) methods, that allow us to define how objects behave in different situations. Among these, __str__ and __repr__ are two important methods used to represent objects as strings.
In this tutorial, we will cover:
__str__ and __repr__?__str__ and __repr____str__ and __repr__?__repr__ (Official String Representation)repr(obj) or in interactive mode__str__ (User-Friendly String Representation)str(obj) or print(obj)__str__ and __repr__| Feature | __repr__ | __str__ |
|---|---|---|
| Purpose | Debugging, development | User-friendly output |
| Output Format | Should be unambiguous | Readable and descriptive |
| Called By | repr(obj), interactive mode | str(obj), print(obj) |
| Example Output | "Student('Amit', 21)" | "Amit (21 years old)" |
__str__ and __repr__class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Student('{self.name}', {self.age})"
def __str__(self):
return f"{self.name} ({self.age} years old)"
# Creating an object
s1 = Student("Amit", 21)
# Using repr()
print(repr(s1)) # Output: Student('Amit', 21)
# Using str()
print(str(s1)) # Output: Amit (21 years old)
# Implicit calls
print(s1) # Output: Amit (21 years old)
s1 # Output: Student('Amit', 21)__repr__ is used for debugging and should return a valid Python expression, while __str__ is more readable for end-users.
__repr__ and __str__?Use __repr__ when:
Use __str__ when:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __repr__(self):
return f"Employee('{self.name}', {self.salary})"
def __str__(self):
return f"{self.name} earns ₹{self.salary}/month"
e1 = Employee("Priya", 50000)
print(repr(e1)) # Output: Employee('Priya', 50000)
print(str(e1)) # Output: Priya earns ₹50000/monthThe __repr__ method provides a developer-friendly format, while __str__ makes the output more user-friendly.
__repr__ → Used for debugging, should be unambiguous__str__ → Used for display, should be user-friendly
If __str__ is not defined, Python falls back to __repr__
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Python Basics
Python is a powerful, high-level programming language known for its simplicity and versatility. It is widely used in various fields, including web development, data science, artificial intelligence, automation, and more. This tutorial series is designed to take you from the basics of Python to more advanced topics, ensuring a strong foundation in programming.