Pythonにおけるマジックメソッド

Pythonにおけるマジックメソッド

この記事ではPythonにおけるマジックメソッドについて説明します。

YouTube Video

Pythonにおけるマジックメソッド

Pythonのマジックメソッド(特殊メソッド)は、クラスに特別な振る舞いを与えるために使用される、特定の名前を持つメソッドです。たとえば、__init____str__ のように、前後に二重のアンダースコア(ダンダー)で囲まれているのが特徴です。そのため、ダンダーメソッドとも呼ばれます。

マジックメソッドを定義することで、クラスに対して標準の振る舞いをカスタマイズできます。たとえば、__add__ を定義すると + 演算子の挙動を変更できます。

初期化と文字列表現のマジックメソッド

__init__: 初期化メソッド

__init__メソッドは、インスタンス生成時に自動的に呼ばれるコンストラクタです。

1class Person:
2    def __init__(self, name, age):
3        self.name = name
4        self.age = age
5
6person = Person("Alice", 30)
7print(person.name)  # Alice

__str__: 人間向けの文字列表現

__str__メソッドは、人間向けの文字列表現を返すメソッドです。print()str()で呼ばれます。

1class Person:
2    def __init__(self, name):
3        self.name = name
4
5    def __str__(self):
6        return f"Person: {self.name}"
7
8person = Person("Bob")
9print(person)  # Person: Bob

__repr__: デバッグ向けの文字列表現

__repr__メソッドは、デバッグ向けの文字列表現を返すメソッドです。repr()やインタプリタでの表示に使用されます。

1class Person:
2    def __init__(self, name):
3        self.name = name
4
5    def __repr__(self):
6        return f"Person(name={self.name!r})"
7
8person = Person("Eve")
9print(repr(person))  # Person(name='Eve')

算術演算子をオーバーロードする

__add__: +演算子

マジックメソッドを利用することで、算術演算子をオーバーロードすることができます。例えば、__add__メソッドは、+演算子をオーバーロードできます。

 1class Vector:
 2    def __init__(self, x, y):
 3        self.x = x
 4        self.y = y
 5
 6    def __add__(self, other):
 7        return Vector(self.x + other.x, self.y + other.y)
 8
 9    def __repr__(self):
10        return f"Vector({self.x}, {self.y})"
11
12    # Other arithmetic magic methods:
13    # def __sub__(self, other):       # Subtraction (-)
14    # def __mul__(self, other):       # Multiplication (*)
15    # def __truediv__(self, other):   # True division (/)
16    # def __floordiv__(self, other):  # Floor division (//)
17    # def __mod__(self, other):       # Modulo (%)
18    # def __pow__(self, other):       # Exponentiation (**)
19
20v1 = Vector(1, 2)
21v2 = Vector(3, 4)
22print(v1 + v2)  # Vector(4, 6)

その他の算術マジックメソッドとして次のようなものがあります。

メソッド 対応演算子
__add__ +
__sub__ -
__mul__ *
__truediv__ /
__floordiv__ //
__mod__ %
__pow__ **

比較演算子のカスタマイズ

比較演算子をオーバーロードすることもできます。例えば、__eq__メソッドは、等価演算子をオーバーロードします。

 1class Box:
 2    def __init__(self, volume):
 3        self.volume = volume
 4
 5    def __eq__(self, other):
 6        return self.volume == other.volume
 7
 8    def __lt__(self, other):
 9        return self.volume < other.volume
10
11    # Comparison magic methods:
12    # def __eq__(self, other):  # Equal to (==)
13    # def __ne__(self, other):  # Not equal to (!=)
14    # def __lt__(self, other):  # Less than (<)
15    # def __le__(self, other):  # Less than or equal to (<=)
16    # def __gt__(self, other):  # Greater than (>)
17    # def __ge__(self, other):  # Greater than or equal to (>=)
18
19b1 = Box(100)
20b2 = Box(200)
21
22print(b1 == b2)  # False
23print(b1 < b2)   # True

他にも次のようなマジックメソッドがあります。これらは、オブジェクトの大小や等価性を定義するためのマジックメソッドです。

演算子 マジックメソッド
== __eq__
!= __ne__
< __lt__
<= __le__
> __gt__
>= __ge__

コンテナ型のマジックメソッド

リストや辞書のようにふるまうクラスを作ることもできます。

__len__: 要素数の取得

__len__メソッドは、要素数を返すマジックメソッドです。

1class Basket:
2    def __init__(self, items):
3        self.items = items
4
5    def __len__(self):
6        return len(self.items)
7
8basket = Basket(["apple", "banana"])
9print(len(basket))  # 2

__getitem__: 添字アクセス

__getitem__メソッドは、添字アクセス時に呼ばれるメソッドです。

1class Basket:
2    def __init__(self, items):
3        self.items = items
4
5    def __getitem__(self, index):
6        return self.items[index]
7
8basket = Basket(["apple", "banana"])
9print(basket[1])  # banana

__setitem____delitem__: 書き込みと削除

__setitem__メソッドと__delitem__メソッドは、書き込みと削除の際に呼ばれるメソッドです。

 1class Basket:
 2    def __init__(self, items):
 3        self.items = items
 4
 5    def __setitem__(self, index, value):
 6        self.items[index] = value
 7
 8    def __delitem__(self, index):
 9        del self.items[index]
10
11basket = Basket(["apple", "banana"])
12basket[1] = "grape"
13del basket[0]
14print(basket.items)  # ['grape']

イテレーションのマジックメソッド

forループなどで反復可能にするには、以下を実装します。

__iter____next__

 1class Counter:
 2    def __init__(self, limit):
 3        self.limit = limit
 4        self.current = 0
 5
 6    def __iter__(self):
 7        return self
 8
 9    def __next__(self):
10        if self.current >= self.limit:
11            raise StopIteration
12        self.current += 1
13        return self.current
14
15for num in Counter(3):
16    print(num)
17# Output:
18# 1
19# 2
20# 3

コンテキストマネージャ(with文)

__enter__メソッドと__exit__メソッドを定義することで、with文での前後処理を実装できます。

 1class FileOpener:
 2    def __init__(self, filename):
 3        self.filename = filename
 4
 5    def __enter__(self):
 6        self.file = open(self.filename, 'r')
 7        return self.file
 8
 9    def __exit__(self, exc_type, exc_val, exc_tb):
10        self.file.close()
11
12with FileOpener("example.txt") as f:
13    content = f.read()
14    print(content)

呼び出し可能オブジェクト:__call__

__call__メソッドを定義することで、関数のようにインスタンスを呼び出すことができます。

1class Greeter:
2    def __init__(self, greeting):
3        self.greeting = greeting
4
5    def __call__(self, name):
6        return f"{self.greeting}, {name}!"
7
8hello = Greeter("Hello")
9print(hello("Alice"))  # Hello, Alice!

まとめ

Pythonのマジックメソッドは、クラスに自然で直感的な振る舞いを追加するための強力な手段です。各メソッドには明確な用途があり、適切に実装することで、より柔軟でPythonicなコードが書けるようになります。

マジックメソッドは「見えないインターフェース」として、Pythonのオブジェクトがどのように連携し、振る舞うかを裏側で支えています。

YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。

YouTube Video