Skip to Content
Fluent Python, 2nd Edition
book

Fluent Python, 2nd Edition

by Luciano Ramalho
April 2022
Intermediate to advanced
1014 pages
23h 59m
English
O'Reilly Media, Inc.
Book available
Content preview from Fluent Python, 2nd Edition

Chapter 12. Special Methods for Sequences

Don’t check whether it is-a duck: check whether it quacks-like-a duck, walks-like-a duck, etc., etc., depending on exactly what subset of duck-like behavior you need to play your language-games with. (comp.lang.python, Jul. 26, 2000)

Alex Martelli

In this chapter, we will create a class to represent a multidimensional Vector class—a significant step up from the two-dimensional Vector2d of Chapter 11. Vector will behave like a standard Python immutable flat sequence. Its elements will be floats, and it will support the following by the end of this chapter:

  • Basic sequence protocol: __len__ and __getitem__

  • Safe representation of instances with many items

  • Proper slicing support, producing new Vector instances

  • Aggregate hashing, taking into account every contained element value

  • Custom formatting language extension

We’ll also implement dynamic attribute access with __getattr__ as a way of replacing the read-only properties we used in Vector2d—although this is not typical of sequence types.

The code-intensive presentation will be interrupted by a conceptual discussion about the idea of protocols as an informal interface. We’ll talk about how protocols and duck typing are related, and its practical implications when you create your own types.

What’s New in This Chapter

There are no major changes in this chapter. There is a new, brief discussion of the typing.Protocol in a tip box near the end of “Protocols and Duck Typing”.

In ...

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.
Start your free trial

You might also like

Fluent Python

Fluent Python

Luciano Ramalho

Publisher Resources

ISBN: 9781492056348Errata PageSupplemental Content