Skip to Content
Fluent Python ―Pythonicな思考とコーディング手法
book

Fluent Python ―Pythonicな思考とコーディング手法

by Luciano Ramalho, 豊沢 聡, 桑井 博之, 梶原 玲子
October 2017
Intermediate to advanced
832 pages
13h 34m
Japanese
O'Reilly Japan, Inc.
Content preview from Fluent Python ―Pythonicな思考とコーディング手法

10章シーケンスをばらして、ハッシュして、スライスする

アヒルかどうかは問題ではありません。あなたのやっている言語ゲームであなたがさせたいアヒルのような習性の部分集合に応じて、アヒルのように「鳴く」か、アヒルのように「歩く」かなどをチェックしてください。

——Alex Martellicomp.lang.python(2000年7月26日)より

本章では、9章の2次元Vector2dから大幅にステップアップして、多次元ベクトルを表現するクラスVectorを作成します。Vectorは、Pythonの標準的で、不変で、フラットなシーケンスと同じように動作します。要素は浮動小数点数です†1。本章の終わりまでに次に示す機能を実装します。

[†1] 監訳注:数学ではベクトルの個々のコンポーネントを「成分」といいますが、ここでは配列やリスト同様に「要素」と書きます。

  • 基本的なシーケンスプロトコルである__len____getitem__
  • 要素数の多いインスタンスを安全に表現
  • 新規のVectorインスタンスを生成する適切なスライスのサポート
  • 収容されているすべての要素の値を考慮に入れたハッシュ集計
  • 書式指定言語をカスタマイズ版に拡張

また、Vector2dで作成した読み取り専用プロパティに替えて、__getattr__を用いた動的な属性アクセスも実装します(シーケンス型ではあまり一般的ではありませんが)。

本章はかなりコード重視になっていますが、途中でちょっと一休みして、非形式的なインタフェースとしてのプロトコルという概念的な話題も取り上げます。そこでは、プロトコルとダックタイピングの関係、そして自分で独自の型を設計するときの実用的な意味も説明します。

それでは始めましょう。

多次元ベクトルアプリケーション ...

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

Using Asyncio in Python

Using Asyncio in Python

Caleb Hattingh
Robust Python

Robust Python

Patrick Viafore

Publisher Resources

ISBN: 9784873118178Other