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 of0x00
values.bytes(string)
: This will encode the given string into bytes. Additional parameters for encoding and error handling will define the details of the encoding process.bytes(something)
: This will invokesomething.__bytes__()
to create a bytes object. The encoding or error arguments will not be used here...