__sizeof__Easy Examples

Returns the memory size of the object in bytes

Implementing __sizeof__

Basic implementation of __sizeof__ in a class.

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

obj = Example()
print(obj)

__sizeof__ returns the memory size of the object in bytes. Implementing it lets you customize how Python interacts with your objects.

__sizeof__ in action

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

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

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

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

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

Want to try these examples interactively?

Open Easy Playground