An explanation of all of Python's 100+ dunder methods and 50+ dunder attributes, including a summary of each one.
Table of contents
- The 3 essential dunder methods 🔑
- Equality and hashability 🟰
- Orderability ⚖️
- Type conversions and string formatting ⚗️
- Context managers 🚪
- Containers and collections 🗃️
- Callability ☎️
- Arithmetic operators ➗
- In-place arithmetic operations ♻️
- Built-in math functions 🧮
- Attribute access 📜
- Metaprogramming 🪄
- Descriptors 🏷️
- Buffers 💾
- Asynchronous operations 🤹
- Construction and finalizing 🏭
- Library-specific dunder methods 🧰
- Dunder attributes 📇
- Every dunder method: a cheat sheet ⭐
The 3 essential dunder methods 🔑
There are 3 dunder methods that most classes should have: __init__
, __repr__
, and __eq__
.
Operation | Dunder Method Call | Returns |
---|---|---|
T(a, b=3) | T.__init__(x, a, b=3) | None |
repr(x) | x.__repr__() | str |
x == y | x.__eq__(y) | Typically bool |
The __init__
method is the initializer (not to be confused with the constructor), the __repr__
method customizes an object's string representation, and the __eq__
method customizes what it means for objects to be equal to one another.
The __repr__
method is particularly helpful at the the Python REPL and when debugging.
Equality and hashability 🟰
In addition to the __eq__ …