Skip to Content
Effective Python 第3版 ―Pythonプログラムを改良する125項目
book

Effective Python 第3版 ―Pythonプログラムを改良する125項目

by Brett Slatkin, 鈴木 駿
October 2025
Intermediate to advanced
572 pages
7h 46m
Japanese
O'Reilly Japan, Inc.
Content preview from Effective Python 第3版 ―Pythonプログラムを改良する125項目

8章メタクラスと属性

メタクラスはPythonの特徴の1つとしてよく言及されますが、メタクラスが実際に何なのかを理解している人はそれほど多くありません。メタクラスという名前†1は、クラスを超越したもの、を意味しますが、漠然としています。簡単に言えば、メタクラスとは、Pythonのclass文に介入して、クラスが定義される際に特別な動きを行う仕組みです。

[†1] 訳注:接頭辞metaは古代ギリシャ語μετ?(あとに)に由来し、転じて「超越した」「高次の」を意味する。

メタクラスと同様に謎めいているのは、Pythonにおける動的な属性参照です。Pythonのオブジェクト指向言語機能と共に、動的な属性参照は、単純なクラスから複雑なクラスへの移行がスムーズに行える強力なツールです。

しかし、メタクラスや動的な属性には落とし穴がたくさんあります。動的な属性を使うと、オブジェクトを上書きしてしまい、予期しない副作用をもたらす可能性があります。メタクラスを使うと、非常に奇妙な動作を引き起こし、理解しがたいコードになる可能性があります。驚き最小の原則にしたがって、よく理解されているイディオムを実装するためにだけ、メタクラスや動的な属性を使うのが重要となります。

項目58 seetterおよびgetterメソッドの代わりにパブリック属性を使う

他のプログラミング言語を経験したことがあるPythonプログラマは、プロテクト属性([項目55]参照)を参照するために、クラスにgetter()メソッドやsetter()メソッドを明示的に実装しようとします。例として、電気回路における抵抗器を模したモデルを実装します。

class OldResistor: def __init__(self, ohms): ...
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

Think Python 第3版 ―コンピュータ科学者の思考で問題を解決する

Think Python 第3版 ―コンピュータ科学者の思考で問題を解決する

Allen B. Downey, 大橋 真也
入門 Python 3 第2版

入門 Python 3 第2版

Bill Lubanovic, 鈴木 駿, 長尾 高弘

Publisher Resources

ISBN: 9784814401338Publisher Website