- 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/monthThe __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
- JavaScript Interview Questions for 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- SQL Interview Questions for 5+ Years Experience
- 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
Random Blogs
- Time Series Analysis on Air Passenger Data
- Government Datasets from 50 Countries for Machine Learning Training
- Google’s Core Update in May 2020: What You Need to Know
- Generative AI - The Future of Artificial Intelligence
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- Data Analytics: The Power of Data-Driven Decision Making
- Grow your business with Facebook Marketing
- What Is SEO and Why Is It Important?
- How AI Companies Are Making Humans Fools and Exploiting Their Data
- What to Do When Your MySQL Table Grows Too Wide
- The Ultimate Guide to Data Science: Everything You Need to Know
- 15 Amazing Keyword Research Tools You Should Explore
- Extract RGB Color From a Image Using CV2
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- 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


