πΉ 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__()
Output:
Alice is 30 years old
π 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}"
Now, when you query:
book = Book.objects.create(title="Django Mastery", author="John Doe")
print(book)
Output in Django Admin / Shell:
Django Mastery by John Doe
πΉ __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__()
Output:
Tesla Model 3 (2024)
Car(model='Tesla Model 3', year=2024)
π 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.
Top comments (0)