- Object-Oriented Programming (OOP) in Python
-
Overview
- Introduction to OOP in Python
- Classes and Objects
- Constructors (__init__) and Destructors
- Inheritance (Single, Multiple, Multilevel)
- Polymorphism and Method Overriding
- Encapsulation and Data Hiding
- Abstract Classes and Interfaces
- Static and Class Methods
- Magic/Dunder Methods (__str__, __repr__)
- Metaclasses in Python
- Method Resolution Order (MRO) in Python
Magic/Dunder Methods (__str__, __repr__)
Add to BookmarkIntroduction
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:
- What are
__str__
and__repr__
? - Differences between
__str__
and__repr__
- How and when to use them
- Real-world examples
1. What Are __str__
and __repr__
?
__repr__
(Official String Representation)
- Used for debugging and logging
- Should return a string that evaluates to a valid object
- Called when using
repr(obj)
or in interactive mode
__str__
(User-Friendly String Representation)
- Used for displaying objects in a readable way
- Called when using
str(obj)
orprint(obj)
- Should return a human-readable string
2. Key Differences Between __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)" |
3. Implementing __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.
4. When to Use __repr__
and __str__
?
Use __repr__
when:
- You need an unambiguous string for debugging/logging
- The output should allow object reconstruction
Use __str__
when:
- You need a human-readable representation
- The object should be printed in a friendly way
5. Real-World Example: Employee Class
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/month
The __repr__
method provides a developer-friendly format, while __str__
makes the output more user-friendly.
6. Summary
__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__
Prepare for Interview
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- Exploratory Data Analysis On Iris Dataset
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- How to Start Your Career as a DevOps Engineer
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Best Platform to Learn Digital Marketing in Free
- How AI Companies Are Making Humans Fools and Exploiting Their Data
- Variable Assignment in Python
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Generative AI - The Future of Artificial Intelligence
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
- Datasets for Speech Recognition Analysis
- Career Guide: Natural Language Processing (NLP)
- Mastering SQL in 2025: A Complete Roadmap for Beginners
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset