__bytes__Easy Examples

Called by bytes(); returns a bytes representation

Implementing __bytes__

Basic implementation of __bytes__ in a class.

python
class Example:
    def __bytes__(self):
        return "Example __bytes__"

obj = Example()
print(obj)

__bytes__ called by bytes(); returns a bytes representation. Implementing it lets you customize how Python interacts with your objects.

__bytes__ in action

Seeing __bytes__ called by Python's built-in operations.

python
# How Python calls __bytes__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __bytes__(self):
        print(f"__bytes__ was called!")
        return self

d = Demo(42)
# This triggers __bytes__:
print(d)

Python automatically calls __bytes__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground