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

Jugurtha Hadjar jugurtha.hadjar at gmail.com
Tue Feb 3 22:12:09 CET 2015


Hello,

I was writing something and thought: Since the class had some 
'constants', and multiple instances would be created, I assume that each 
instance would have its own data. So this would mean duplication of the 
same constants? If so, I thought why not put the constants in memory 
once, for every instance to access (to reduce memory usage).

Correct me if I'm wrong in my assumptions (i.e: If instances share stuff).

So I investigated further..

 >>> import sys
 >>> sys.getsizeof(5)
12


So an integer on my machine is 12 bytes.

Now:

 >>> class foo(object):
...	def __init__(self):
...		pass

 >>> sys.getsizeof(foo)
448		

 >>> sys.getsizeof(foo())
28

 >>> foo
<class '__main__.foo'>
 >>> foo()
<__main__.foo object at 0xXXXXXXX


- Second weird thing:

 >>> class bar(object):
...	def __init__(self):
...		self.w = 5
...		self.x = 6
...		self.y = 7
...		self.z = 8

 >>> sys.getsizeof(bar)
448
 >>> sys.getsizeof(foo)
448
 >>> sys.getsizeof(bar())
28
 >>> sys.getsizeof(foo())
28

 >>> sys.getsizeof(bar().x)
12
 >>> sys.getsizeof(bar().y)
12


Summary questions:

1 - Why are foo's and bar's class sizes the same? (foo's just a nop)
2 - Why are foo() and bar() the same size, even with bar()'s 4 integers?
3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers?



Thanks..

-- 
~Jugurtha Hadjar,


More information about the Tutor mailing list