- 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__)
Introduction
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
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Top 15 Recommended SEO Tools
- Data Analytics: The Power of Data-Driven Decision Making
- AI in Cybersecurity: The Future of Digital Protection
- Datasets for Speech Recognition Analysis
- How to Start Your Career as a DevOps Engineer
- 15 Amazing Keyword Research Tools You Should Explore
- Best Platform to Learn Digital Marketing in Free
- Why to learn Digital Marketing?
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Avoiding the Beginner’s Trap: Key Python Fundamentals You Shouldn't Skip
- Big Data: The Future of Data-Driven Decision Making
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Python Challenging Programming Exercises Part 2
- What Is SEO and Why Is It Important?
Datasets for Machine Learning
- 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
- Bitcoin Heist Ransomware Address Dataset