Defining Custom Representations
Implementing Custom String Methods
Customizing object string representations allows you to control how objects are displayed and provide meaningful information.
Implementing __str__()
Method
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
def __str__(self):
return f"{self.title} by {self.author} ({self.year})"
book = Book("Python Mastery", "John Smith", 2023)
print(str(book)) ## Outputs: Python Mastery by John Smith (2023)
Implementing __repr__()
Method
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
def __repr__(self):
return f"Book(title='{self.title}', author='{self.author}', year={self.year})"
book = Book("Python Mastery", "John Smith", 2023)
print(repr(book)) ## Detailed representation
Representation Method Hierarchy
graph TD
A[Object String Representation] --> B{__str__() Method}
B -->|Exists| C[Return User-Friendly String]
B -->|Not Found| D{__repr__() Method}
D -->|Exists| E[Return Detailed String]
D -->|Not Found| F[Return Default Memory Address]
Best Practices for Custom Representations
Practice |
Description |
Example |
Clarity |
Provide meaningful information |
Include key object attributes |
Consistency |
Maintain a standard format |
Use similar structure across classes |
Debugging |
Enable easy object inspection |
Include unique identifiers |
Advanced Representation Techniques
class ComplexData:
def __init__(self, data):
self.data = data
def __str__(self):
return f"Data: {len(self.data)} items"
def __repr__(self):
return f"ComplexData(data={self.data})"
By mastering custom representations, you can create more informative and debuggable Python objects. LabEx recommends practicing these techniques to improve your object-oriented programming skills.