Skip to Content
Fluent Python
book

Fluent Python

by Luciano Ramalho
August 2015
Intermediate
790 pages
18h 48m
English
O'Reilly Media, Inc.
Content preview from Fluent Python

Chapter 9. A Pythonic Object

Never, ever use two leading underscores. This is annoyingly private.1

Ian Bicking, Creator of pip, virtualenv, Paste and many other projects

Thanks to the Python data model, your user-defined types can behave as naturally as the built-in types. And this can be accomplished without inheritance, in the spirit of duck typing: you just implement the methods needed for your objects to behave as expected.

In previous chapters, we presented the structure and behavior of many built-in objects. We will now build user-defined classes that behave as real Python objects.

This chapter starts where Chapter 1 ended, by showing how to implement several special methods that are commonly seen in Python objects of many different types.

In this chapter, we will see how to:

  • Support the built-in functions that produce alternative object representations (e.g., repr(), bytes(), etc).

  • Implement an alternative constructor as a class method.

  • Extend the format mini-language used by the format() built-in and the str.format() method.

  • Provide read-only access to attributes.

  • Make an object hashable for use in sets and as dict keys.

  • Save memory with the use of __slots__.

We’ll do all that as we develop a simple two-dimensional Euclidean vector type.

The evolution of the example will be paused to discuss two conceptual topics:

  • How and when to use the @classmethod and @staticmethod decorators.

  • Private and protected attributes in Python: usage, conventions, and limitations. ...

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, 2nd Edition

Fluent Python, 2nd Edition

Luciano Ramalho

Publisher Resources

ISBN: 9781491946237Errata Page