dunder メソッド("double underscore" の略。マジックメソッド/特殊メソッドとも呼ばれる)は、__init__、__str__、__len__ のような特別な名前を持つメソッドで、オブジェクトを Python のと統合できるようにします。Python は構文に応じてこれらを自動的に呼び出します。例えば は を呼び出します。
len(obj)obj.__len__()class Vector:
def __init__(self, x, y): # constructor — Vector(1, 2)
self.x, self.y = x, y
def __repr__(self): # repr(v) and the REPL — for developers
return f"Vector({self.x}, {self.y})"
def __str__(self): # str(v) / print(v) — for users
return f"({self.x}, {self.y})"
def __add__(self, other): # enables the + operator: v1 + v2
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other): # enables ==
return self.x == other.x and self.y == other.y
v1, v2 = Vector(1, 2), Vector(3, 4)
v1 + v2 # Vector(4, 6) — calls __add__
print(v1) # (1, 2) — calls __str__
v1 == Vector(1, 2) # True — calls __eq__
これらを定義すると、自作のオブジェクトが組み込み型と同じようにネイティブな構文(+、==、print)で動作するようになります。
__init__ → constructor (object creation)
__repr__ → unambiguous developer representation (debugging, REPL)
__str__ → readable user-facing string (print, str())
__len__ → len(obj)
__getitem__→ obj[key] (indexing/subscripting)
__iter__ / __next__ → make an object iterable (for loops)
__eq__, __lt__, __gt__ → comparison operators (==, <, >)
__add__, __sub__, __mul__ → arithmetic operators
__call__ → make an instance callable like a function: obj()
__contains__ → the `in` operator
__enter__ / __exit__ → context managers (with statement)
class Deck:
def __init__(self): self.cards = [...]
def __len__(self): return len(self.cards) # len(deck)
def __getitem__(self, i): return self.cards[i] # deck[0], and iteration/slicing!
deck = Deck()
len(deck) # works
for card in deck: # __getitem__ makes it iterable too
...
__len__ と __getitem__ を実装すると、そのオブジェクトはシーケンスのように振る舞い、len()、添字アクセス、イテレーション、スライスをサポートします。
dunder メソッドは、Python が一貫した「すべてはオブジェクト」という感覚を実現する方法です。自作のクラスを、言語の演算子や組み込み関数(+、==、len()、for、[]、with、print)とシームレスに統合できるようにします。
これは、Python のエレガントで多態的な設計(「ダックタイピング」+データモデル)の基盤です。
主要な dunder — とりわけ __init__、__repr__/__str__、比較・算術演算子、そしてイテレーションプロトコル — を知っておくことで、ネイティブ型のように感じられる直感的で Python 的なクラスを構築できるようになり、言語の構文が内部でどうメソッド呼び出しにマッピングされるのかが理解できます。