sys.getsizeof
returns a number which is more specialized and less useful than people think. In fact, if you increase the number of attributes to six, your test3_obj remains at 32, but test4_obj jumps to 48 bytes. This is because getsizeof is returning the size of the PyObject structure implementing the type, which for test3_obj doesn’t include the dict holding the attributes, but for test4_obj, the attributes aren’t stored in a dict, they are stored in slots, so they are accounted for in the size.
But a class defined with __slots__
takes less memory than a class without, precisely because there is no dict to hold the attributes.
Why override __sizeof__
? What are you really trying to accomplish?