English
Summary
Conclusions
A special method is part of the language contract. It lets you use a class as a value, container, or resource if its behavior meets expectations. Dataclass removes repetition from code, and an enumeration makes valid states explicit. Immutability, equality, and hashing must be designed together.
Self-check questions
- Where does Python look for the special method for
len? - How do
repr,str, andformatdiffer? - Why does an arithmetic method return
NotImplemented? - When can the right type's reflected method take priority?
- Does
+=always preserve object identity? - What is the relationship between equality and hashing?
- Why is a mutable key dangerous for a dictionary?
- What does
__getitem__receive for a slice? - How can you provide two independent traversals of a container?
- What should
__exit__return to avoid hiding a failure? - Which methods does dataclass generate by default?
- Why is
default_factorybetter than a shared list? - Does
frozenmake nested fields immutable? - When do you need
Enum,StrEnum, andFlag? - How does
__match_args__affect positional patterns?