Customizing Object Representation
Implementing repr() Method
Custom object representation is achieved by defining the __repr__()
method in your class. This method allows you to control how your object is represented when repr()
is called.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
## Creating an instance
user = Person("LabEx Developer", 30)
print(repr(user)) ## Output: Person(name='LabEx Developer', age=30)
Advanced Representation Techniques
Complex Object Representation
class ComplexData:
def __init__(self, data):
self.data = data
def __repr__(self):
## Detailed representation of complex objects
return f"ComplexData(items={len(self.data)})"
complex_obj = ComplexData([1, 2, 3, 4, 5])
print(repr(complex_obj)) ## Output: ComplexData(items=5)
Representation Strategies
graph TD
A[Representation Strategies]
A --> B[Debugging Info]
A --> C[Recreatable Syntax]
A --> D[Concise Summary]
Best Practices for repr()
Practice |
Description |
Example |
Be Precise |
Show key object details |
__repr__() returns exact structure |
Use Eval-Compatible |
Create representable string |
Can be used with eval() |
Include Crucial Data |
Highlight important attributes |
Show key object properties |
Handling Different Data Types
class DataContainer:
def __init__(self, data_type, content):
self.data_type = data_type
self.content = content
def __repr__(self):
## Flexible representation based on data type
return f"DataContainer(type={self.data_type}, content={repr(self.content)})"
## Examples
text_data = DataContainer('text', 'Hello, LabEx!')
numeric_data = DataContainer('number', [1, 2, 3])
print(repr(text_data)) ## Detailed text representation
print(repr(numeric_data)) ## Detailed numeric representation
- Keep
__repr__()
method lightweight
- Avoid complex computations
- Focus on essential object information
Common Pitfalls to Avoid
- Revealing sensitive information
- Creating overly complex representations
- Inconsistent representation across object instances
By mastering custom object representation, developers can create more informative and debuggable Python classes.