Skip to Content
『Learning Python 第6版』
book

『Learning Python 第6版』

by Mark Lutz
March 2025
Intermediate to advanced
1172 pages
24h 57m
Japanese
O'Reilly Media, Inc.
Content preview from 『Learning Python 第6版』

第30章 演算子のオーバーロード 演算子のオーバーロード

この作品はAIを使って翻訳されている。ご意見、ご感想をお待ちしている:translation-feedback@oreilly.com

この章では、演算子のオーバーロードに焦点を当て、クラス・メカニズムに関する詳細な調査を続ける。前の章では、演算子のオーバーロードについて簡単に説明した。ここでは、さらに詳細を詰め、よく使われるオーバーロード・メソッド(そのほとんどはまだ遭遇したことがないもの)を探っていく。多くの演算子オーバーロードメソッドのそれぞれをデモするスペースはないが、ここでコーディングするものは、このPythonクラスの機能の可能性を明らかにするのに十分な代表的なサンプルである。

基本

演算子のオーバーロード」とは、簡単に言うと 、クラスのメソッドに組み込みの演算子を取り込むことだ。組み込みの演算子でクラスのインスタンスが現れると、Pythonは自動的にあなたのメソッドを呼び出し、あなたのメソッドの戻り値が対応する演算の結果になる。ここでは、オーバーロードの背後にある重要なアイデアをおさらいしよう:

  • 演算子オーバーロードは、クラスが通常のPython操作を傍受することを可能にする。

  • クラスはすべてのPython組み込み式演算子をオーバーロードできる。

  • クラスは、印刷、関数呼び出し、属性アクセスなど、他の組み込み関数の呼び出しもオーバーロードできる。

  • オーバーロードは、クラス内に特殊メソッド名を付けることで実装される。

  • Pythonは組み込み演算子に対応する特殊メソッド名をあらかじめ定義している。

言い換えると、あらかじめ定義された特殊な名前のメソッドがクラスに用意されている場合、Pythonはそのクラスのインスタンスが関連する組み込み演算子や演算式に現れると、自動的にそのメソッドを呼び出す。あなたのクラスは、そのクラスから作成されたインスタンスオブジェクトに対して、対応する演算の振る舞いを提供する。

学習したように、演算子オーバーロード・メソッドは決して必須ではなく、一般的にデフォルトもない(すべてのクラスが暗黙のobject ルート・クラスから取得する一握りのメソッドを除けば)。もしオーバーロードメソッドをコーディングしなかったり継承しなかったりした場合、それは単にあなたのクラスが対応する演算子をサポートしていないことを意味する。しかし、これらのメソッドを使うことで、クラスは組み込みオブジェクトのインタフェースをエミュレートすることができる。

コンストラクタと式:init__と __sub__

ウォームアップとして、例30-1のシンプルなクラスを考えてみよう。Number クラスは、モジュールファイルnumber.py の でコードされ、インスタンス構築 (__init__) をインターセプトするメソッドと、減算式 (__sub__) をキャッチするメソッドを提供する。これらのような特殊メソッドは、組み込み演算子に結びつけるためのフックである。

例 30-1. number.py
class Number:
    def __init__(self, start):                  # On Number(start)
        self.data = start
    def __sub__(self, other):                   # On instance - other
        return Number(self.data - other)        # Result is a new instance

すでに学んだように、このコードで見られる ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python Polars ―高速なデータ処理を実現する次世代ライブラリ

Python Polars ―高速なデータ処理を実現する次世代ライブラリ

Jeroen Janssens, Thijs Nieuwdorp, 中田 秀基
入門 Python 3 第2版

入門 Python 3 第2版

Bill Lubanovic, 鈴木 駿, 長尾 高弘

Publisher Resources

ISBN: 9798341634367