Skip to content

[Edit] Python: dunder-methods __str__() #6623

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 24, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 157 additions & 19 deletions content/python/concepts/dunder-methods/terms/str/str.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,185 @@ Description: 'Returns a reader-friendly string representation of a class object.
Subjects:
- 'Computer Science'
- 'Data Science'
- 'Web Development'
Tags:
- 'Attributes'
- 'Classes'
- 'Functions'
- 'Methods'
- 'Objects'
- 'OOP'
- 'Strings'
CatalogContent:
- 'learn-python-3'
- 'paths/computer-science'
---

The **`__str__()`** dunder method returns a reader-friendly string representation of a class object. It can be called with the built-in [`str()`](https://www.codecademy.com/resources/docs/python/built-in-functions/str) and [`print()`](https://www.codecademy.com/resources/docs/python/built-in-functions/print) functions. Unlike [`__repr__()`](https://www.codecademy.com/resources/docs/python/dunder-methods/repr), it is not necessary that `__str__()` return a valid Python expression.
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()`](https://www.codecademy.com/resources/docs/python/built-in-functions/str) and [`print()`](https://www.codecademy.com/resources/docs/python/built-in-functions/print) functions. Unlike [`__repr__()`](https://www.codecademy.com/resources/docs/python/dunder-methods/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

```pseudo
class ClassName:
def __str__(self):
# Return a string representation of the object
return string
```

The `__str__()` method accepts no parameters. `self` is an implicit reference to the instance of `ClassName`.
**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:

## Codebyte Example
- `__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:

```py
class Student:
def __init__(self, name, student_id, gpa):
# Initialize student attributes
self.name = name
self.student_id = student_id
self.gpa = gpa

def __str__(self):
# Return a readable string representation
return f"Student: {self.name}, ID: {self.student_id}, GPA: {self.gpa}"

The example below showcases various ways the `__str__()` can be called using an object literal, the built-in `str()` function, and the `__str__()` dunder method. All return the same string output; the aim is to make the output readable:
# Create a student object
student = Student("Alice Smith", 12345, 3.8)

# The __str__ method is called when printing the object
print(student)

# It's also called when using the str() function
print(str(student))
```

Output generated by this code will be:

```shell
Student: Alice Smith, ID: 12345, GPA: 3.8
Student: 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:

```py
class Product:
def __init__(self, name, price, quantity):
# Initialize product attributes
self.name = name
self.price = price
self.quantity = quantity

def __str__(self):
# Format product information as a readable string
return f"{self.name} - ${self.price:.2f} (Quantity: {self.quantity})"

def __repr__(self):
# Developer-focused representation
return f"Product('{self.name}', {self.price}, {self.quantity})"

# Create some products
laptop = 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 output
print("\nRepr Output:")
print(repr(laptop))
print(repr(headphones))
```

Output of this code will look like:

```shell
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:

```codebyte/python
class Home:
def __init__(self, rooms, stories):
self.rooms = rooms
self.stories = stories
class Book:
def __init__(self, title, author, pages):
# Initialize book attributes
self.title = title
self.author = author
self.pages = pages

def __str__(self):
return "The house has {} rooms and {} stories".format(self.rooms, self.stories)
def __str__(self):
# Human-readable string for end users
return f"'{self.title}' by {self.author}, {self.pages} pages"

def __repr__(self):
# Formal string for developers
return f"Book('{self.title}', '{self.author}', {self.pages})"

# Create a new book
book = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 224)

home = Home(4, 2)
# Use print() function which implicitly calls __str__
print("Book Information:")
print(book)

print(home)
print(str(home))
print(home.__str__())
# Use both str() and repr() functions explicitly
print("\nString representations:")
print(f"str(): {str(book)}")
print(f"repr(): {repr(book)}")

# Create a list of books and print it
books = [
Book("1984", "George Orwell", 328),
Book("To Kill a Mockingbird", "Harper Lee", 281)
]
print("\nBook Collection:")
for book in books:
print(book) # __str__ is called for each book
```

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.