Lesson explanation
After this lesson, you will be able to:
__str__.__str__ and the developer-oriented __repr__.@dataclass with typed fields.Python calls methods with names like __str__ and __repr__ dunder methods (short for double underscore). str(obj) and print(obj) use __str__ when present. repr(obj) is intended to help developers inspect an object; by default, Python may show a generic class-and-address representation.
For data-focused classes, @dataclass from dataclasses automatically creates common methods based on declared, type-annotated fields. This includes an initializer, a useful representation, and value-based equality (==). Type annotations describe fields; they do not automatically validate types at runtime.
You can still define your own __str__ on a dataclass to control display while keeping its generated initializer and equality. Prefer dataclasses for simple structured records; keep complex behavior inside ordinary classes when it adds clarity.
__str__class Server:
def __init__(self, name, region):
self.name = name
self.region = region
def __str__(self):
return f"{self.name}@{self.region}"
print(Server("worker", "eu"))Output:
worker@eu__str__ must return a string, not print it.
This class defines both representations for different audiences.
class Build:
def __init__(self, number):
self.number = number
def __str__(self):
return f"Build #{self.number}"
def __repr__(self):
return f"Build(number={self.number})"
build = Build(9)
print(str(build))
print(repr(build))Output:
Build #9
Build(number=9)@dataclass create the initializerfrom dataclasses import dataclass
@dataclass
class Job:
name: str
retries: int
job = Job("backup", 2)
print(job.name)
print(repr(job))Output:
backup
Job(name='backup', retries=2)The fields automatically become constructor parameters.
Two different instances can still represent equal data.
from dataclasses import dataclass
@dataclass
class Version:
component: str
major: int
first = Version("api", 2)
second = Version("api", 2)
print(first == second)
print(first is second)Output:
True
False| Need | Python |
|---|---|
| Human-friendly string | __str__(self) returns text |
| Developer representation | __repr__(self) returns text |
| Data-record constructor | @dataclass with annotated fields |
| Same field values | first == second |
| Exact same object | first is second |
None from __str__; Python requires a string.is to compare independent data records by value.@dataclass prevents writing custom methods; you can still customize behavior.