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. ...

Get Fluent Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.