The __bytes__() method

There are relatively few occasions to transform an object into bytes. We'll look at this in detail in Part 2, Persistence and Serialization.

In the most common situation, an application can create a string representation, and the built-in encoding capabilities of the Python IO classes will be used to transform the string into bytes. This works perfectly for almost all situations. The main exception would be when we're defining a new kind of string. In that case, we'd need to define the encoding of that string.

The bytes() function does a variety of things, depending on the arguments:

  • bytes(integer): This returns an immutable bytes object with the given number of 0x00 values.
  • bytes(string): This will encode the given string into ...

Get Mastering Object-oriented 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.