0
class test:
    x = []
    def __init__(self, n):
        x = list(range(n))

z=test(500)
sys.getsizeof(z)
56

sys.getsizeof(z.x)
4608

This is not consistent. I need to compute the size of an object I created. How do I do that?

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
Bing Bang
  • 524
  • 7
  • 16
  • You can't. Objects don't necessarily have unique owners. – Sven Marnach Jan 27 '15 at 17:25
  • 1
    `x` is a local variable in `__init__`, so `z.x` is `[]`. – interjay Jan 27 '15 at 17:27
  • What do you mean *"not consistent"*? The size of `z` doesn't include the size of `x` because `z` just contains a *reference* to the list (which may also be referenced elsewhere). – jonrsharpe Jan 27 '15 at 17:29
  • So if I need to know how much memory I need to instantiate a new object with all new internal objects, I have to add up all the sizes of any internal objects, recursively if need be? Seems like a lot of work! – Bing Bang Jan 27 '15 at 18:01
  • @Bing Bang I use this code to know the size of any object recursively: [link](https://goshippo.com/blog/measure-real-size-any-python-object/) – Raphael Nov 08 '19 at 14:40

0 Answers0