DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

What is `__str__()` (dunder string function) in Python?

🔹 What is __str__() in Python?

__str__() is a special (dunder) method in Python that defines the string representation of an object when print(object) or str(object) is called.


READ complete this article on this link

🔹 Why Use __str__()?

  • ✅ Makes objects human-readable when printed.
  • ✅ Useful for debugging (instead of memory addresses).
  • ✅ Customizes how an object is displayed in logs or Django Admin.

🔹 Example: Using __str__() in a Class

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} is {self.age} years old"

person = Person("Alice", 30)
print(person)  # Calls __str__()
Enter fullscreen mode Exit fullscreen mode

Output:

Alice is 30 years old
Enter fullscreen mode Exit fullscreen mode

🚀 Now, print(person) displays a meaningful message instead of <__main__.Person object at 0x7f8b3e4c9d00>.


🔹 __str__() in Django Models

Django models use __str__() to define how objects appear in Django Admin and QuerySets.

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=255)

    def __str__(self):
        return f"{self.title} by {self.author}"
Enter fullscreen mode Exit fullscreen mode

Now, when you query:

book = Book.objects.create(title="Django Mastery", author="John Doe")
print(book)
Enter fullscreen mode Exit fullscreen mode

Output in Django Admin / Shell:

Django Mastery by John Doe
Enter fullscreen mode Exit fullscreen mode

🔹 __str__() vs __repr__()

Method Purpose
__str__() User-friendly string representation (used in print())
__repr__() Developer-friendly debugging representation (used in repr())

Example:

class Car:
    def __init__(self, model, year):
        self.model = model
        self.year = year

    def __str__(self):
        return f"{self.model} ({self.year})"

    def __repr__(self):
        return f"Car(model='{self.model}', year={self.year})"

car = Car("Tesla Model 3", 2024)
print(str(car))   # Calls __str__()
print(repr(car))  # Calls __repr__()
Enter fullscreen mode Exit fullscreen mode

Output:

Tesla Model 3 (2024)
Car(model='Tesla Model 3', year=2024)
Enter fullscreen mode Exit fullscreen mode

🚀 Summary

✅ __str__() makes objects human-readable when printed.

✅ It is commonly used in Django models to make query results readable.

✅ __repr__() is used for developer-friendly debugging.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay