Special Method Protocols

__bytes__() — object lifecycle protocol

Provide byte conversion for bytes(obj). It must return bytes; the hook decides encoding or binary representation. It is not automatically equivalent to encoding str(obj).

Formal Syntax & Structure

python syntaxpython
def __bytes__(self):

Return Value

bytes

Binary representation.

Working Example

Example Snippetpython
class Tag:    def __bytes__(self): return b"TAG"print(bytes(Tag()))
Python Reference