6
import sys


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y


v1 = Vector(1, 2)
v2 = Vector(1, 2)
print(f"v1 __dict__ : {sys.getsizeof(v1.__dict__)} bytes")
print(f"v2 __dict__ : {sys.getsizeof(v2.__dict__)} bytes")

v3 = Vector(1, 2)
v4 = Vector(1, 2)
print(f"v3 __dict__ : {sys.getsizeof(v3.__dict__)} bytes")
print(f"v4 __dict__ : {sys.getsizeof(v4.__dict__)} bytes")

v5 = Vector(1, 2)
print(f"v5 __dict__ : {sys.getsizeof(v5.__dict__)} bytes")

v6 = Vector(1, 2)
print(f"v6 __dict__ : {sys.getsizeof(v6.__dict__)} bytes")

Anyone can tell me why the result of the code above is

v1 __dict__ : 288 bytes
v2 __dict__ : 288 bytes
v3 __dict__ : 272 bytes
v4 __dict__ : 272 bytes
v5 __dict__ : 264 bytes
v6 __dict__ : 256 bytes

I try to ask AI and the explanation seems to be strange and i can't understand that clearly.

and if I move the print statement up and down ,it will lead to different results,so why this matters?

Why v2 and v3 differ?

I found the code acts differently from various python versions,and the result above is in Python3.13

A really strange phenomenon for me ,thank you all .

10
  • This question is similar to: Why is the __dict__ of instances so much smaller in size in Python 3?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jun 27 at 11:54
  • 2
    @user2722968 This question isn't about the difference between python versions, it's about the difference between instances in the same version. Commented Jun 27 at 13:55
  • 1
    See also: sys.getsizeof is not what you want that alludes to internal book keeping and overallocation of memory Commented Jun 27 at 14:57
  • 2
    @Barmar the answer that explains the split table implementation for key-sharing attribute dicts may actually be the answer here, though I think this could serve as an independent question and shouldn't be closed as a duplicate. Commented Jun 27 at 15:26
  • 1
    Running it longer shows me that the size shrinks by 8 bytes for each new instance until it reaches 88 bytes. Commented Jun 27 at 17:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.