Python __str__()
The __str__() dunder method, also known as a magic method, returns a human-readable string representation of a class object. It can be called with the built-in str() and print() functions. Unlike __repr__(), it is not necessary that __str__() will return a valid Python expression.
In Python, objects can be represented as strings to make them more meaningful and easier to read. The __str__() method is one of Python’s special methods, also known as dunder methods (double underscore methods). It allows defining how an object should be converted to a string when used with str() function or when displayed using print(). This method is particularly helpful in debugging and logging purposes, as well as for providing user-friendly representations of custom objects.
Syntax
class ClassName:
def __str__(self):
# Return a string representation of the object
return string
Parameters:
self: An implicit reference to the instance of the class.
The __str__() method accepts no parameters other than the implicit self reference.
Return value:
It must return a string that represents the object in a human-readable format.
Difference between __str__() and __repr__()
The __str__() and __repr__() methods both return string representations of objects, but they serve different purposes:
__str__(): Returns a human-readable, informal string representation intended for end users. It prioritizes readability over completeness.__repr__(): Returns an information-rich, official string representation intended for developers. Where possible, it should return a valid Python expression which can be used to recreate the object.
In general, __str__() is meant for users, while __repr__() is meant for developers. If a class defines __str__() but not __repr__(), the built-in object implementation calls __repr__() method instead when using the repr() function.
Example 1: Creating a Student Object
This example demonstrates how to implement the __str__() method in a class to provide a readable string representation of a student object:
class Student:def __init__(self, name, student_id, gpa):# Initialize student attributesself.name = nameself.student_id = student_idself.gpa = gpadef __str__(self):# Return a readable string representationreturn f"Student: {self.name}, ID: {self.student_id}, GPA: {self.gpa}"# Create a student objectstudent = Student("Alice Smith", 12345, 3.8)# The __str__ method is called when printing the objectprint(student)# It's also called when using the str() functionprint(str(student))
Output generated by this code will be:
Student: Alice Smith, ID: 12345, GPA: 3.8Student: Alice Smith, ID: 12345, GPA: 3.8
In this example, the __str__() method formats the student’s information into a human-readable string. When the object is displayed or converted to a string, Python automatically calls the __str__() method.
Example 2: Product Inventory Display
This example shows how to implement __str__() in a product inventory system where there is a need to display product information in a readable format:
class Product:def __init__(self, name, price, quantity):# Initialize product attributesself.name = nameself.price = priceself.quantity = quantitydef __str__(self):# Format product information as a readable stringreturn f"{self.name} - ${self.price:.2f} (Quantity: {self.quantity})"def __repr__(self):# Developer-focused representationreturn f"Product('{self.name}', {self.price}, {self.quantity})"# Create some productslaptop = Product("Laptop", 999.99, 10)headphones = Product("Headphones", 59.99, 25)# Display products using __str__print("Available Products:")print(laptop)print(headphones)# Compare with repr outputprint("\nRepr Output:")print(repr(laptop))print(repr(headphones))
Output of this code will look like:
Available Products:Laptop - $999.99 (Quantity: 10)Headphones - $59.99 (Quantity: 25)Repr Output:Product('Laptop', 999.99, 10)Product('Headphones', 59.99, 25)
This example demonstrates how __str__() provides a user-friendly format for displaying product information, while __repr__() gives a representation that could be used to recreate the objects programmatically.
Codebyte Example: Creating a Custom Book Class
This example demonstrates the implementation of __str__() for a Book class, allowing for intuitive string representation when displaying book information:
This example demonstrates how the __str__() method provides a user-friendly representation of books, which is automatically used when printing the objects or when using the str() function.
Frequently Asked Questions
1. Does print use __str__() or __repr__()?
The print() function uses __str__() if it’s defined. If __str__() is not defined, it falls back to using __repr__(). This behavior ensures that an object can always be printed, even if the developer has only defined one of these methods.
2. What is the difference between __str__() and __init__()?
The __init__() method is a constructor that initializes a new instance of a class with provided values. It runs when an object is created and sets up the object’s initial state. The __str__() method, on the other hand, defines how an object should be converted to a string when using functions like str() or print(). They serve entirely different purposes: __init__() for object creation and __str__() for string representation.
3. What happens if __str__() is not defined?
If a class doesn’t define the __str__() method, Python will use the __repr__() method instead when str() or print() is called on an instance of the class. If neither __str__() nor __repr__() is defined, Python will use the default implementation from the object class, which typically returns a string like <__main__.ClassName object at 0x7f042103f390> showing the class name and memory address.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours