[Tutor] Why is an instance smaller than the sum of its components?

Danny Yoo dyoo at hashcollision.org
Tue Feb 3 22:57:45 CET 2015


>>>> class bar(object):
> ...     def __init__(self):
> ...             self.w = 5
> ...             self.x = 6
> ...             self.y = 7
> ...             self.z = 8
>
>>>> sys.getsizeof(bar())
> 28
> 3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers?


But what is the documented behavior of sys.getsizeof?

Reading...

    https://docs.python.org/3/library/sys.html#sys.getsizeof

Ah.  The following phrase in the documentation seems to apply directly
to your question:

"Only the memory consumption directly attributed to the object is
accounted for, not the memory consumption of objects it refers to."

But the docs there also have a link to a recursive getsizeof() recipe
that does what I think you intend.  Take a look at that recipe.


Good luck!


More information about the Tutor mailing list