How To Use the __str__() and __repr__() Methods in Python
In Python, the __str__() and __repr__() methods are special methods used to define how objects are represented as strings. These methods are crucial for debugging and logging, making it easier to understand the output of objects. This tutorial provides a comprehensive guide on how to use these methods effectively.
Understanding the __str__() Method Copy link
The __str__() method in Python is used to create a string representation of an object that is readable and user-friendly. This method is invoked when str() or print() functions are called on an object.
Syntax
class ClassName:
def __str__(self):
return "string_representation"
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
person = Person("Alice", 30)
print(person) # Output: Person(name=Alice, age=30)
Output:
Understanding the __repr__() Method Copy link
The __repr__() method is used to create a string representation of an object that is more detailed and unambiguous. This method is intended for developers and is used when repr() function is called, or when the object is inspected in the interactive interpreter.
Syntax
class ClassName:
def __repr__(self):
return "detailed_representation"
Example
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})"
person = Person("Alice", 30)
print(repr(person)) # Output: Person(name='Alice', age=30)
Output:
Key Differences Between __str__() and __repr__() Copy link
Purpose:
__str__()is for creating a readable representation of an object for end-users.__repr__()is for creating a detailed and precise representation for developers.
Usage:
__str__()is called by theprint()andstr()functions.__repr__()is called by therepr()function and the interactive interpreter.
Output:
__str__()should be user-friendly and easy to read.__repr__()should be unambiguous and often includes additional information useful for debugging.
Best Practices for Using __str__() and __repr__() Copy link
- Implement Both Methods: It is recommended to implement both
__str__()and__repr__()methods to provide clear and useful string representations of objects. - Ensure Readability: Make sure that the output of
__str__()is easy to read and understand. - Include All Relevant Information: The
__repr__()method should include all necessary details about the object for debugging purposes. - Use F-strings: Utilize Python f-strings for better readability and performance when formatting strings.
Examples of Using __str__() and __repr__() Copy link
Example 1: Basic Class Implementation
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __str__(self):
return f"{self.year} {self.make} {self.model}"
def __repr__(self):
return f"Car(make='{self.make}', model='{self.model}', year={self.year})"
car = Car("Toyota", "Corolla", 2020)
print(car) # Output: 2020 Toyota Corolla
print(repr(car)) # Output: Car(make='Toyota', model='Corolla', year=2020)
Output:
Example 2: Customizing String Representation
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __str__(self):
return f"{self.real} + {self.imag}i"
def __repr__(self):
return f"ComplexNumber(real={self.real}, imag={self.imag})"
complex_num = ComplexNumber(3, 4)
print(complex_num) # Output: 3 + 4i
print(repr(complex_num)) # Output: ComplexNumber(real=3, imag=4)
Output:
Conclusion Copy link
The __str__() and __repr__() methods in Python play a significant role in providing meaningful string representations of objects. Implementing these methods enhances the readability and debuggability of code, making it easier to work with complex objects. By following the best practices outlined in this tutorial, developers can effectively use these methods to improve their Python applications.
On our app platform you can find Python applications, such as Celery, Django, FastAPI and Flask.