nda
nda

Reputation: 561

Why do different classes take the same amount of memory?

Why does foo not take more memory if it has another variable?

class Foo():
  a = 1
  b = 1

class Bar():
  a = 1

import sys

foo = Foo()
print(sys.getsizeof(foo))  # 56
bar = Bar()
print(sys.getsizeof(bar))  # 56

Upvotes: 4

Views: 196

Answers (1)

chepner
chepner

Reputation: 532368

First, methods are stored with the type of the object, not the object itself.

However, you'll notice that if you ask for the class sizes, they are equal as well.

>>> sys.getsizeof(Foo)
1064
>>> sys.getsizeof(Bar)
1064

Each class object has a __dict__ attribute that stores references to its methods and other attributes.

>>> Foo.__dict__['why_does_this_not_use_take_memory']
<function Foo.why_does_this_not_use_take_memory at 0x103609ef0>

However, sys.getsizeof doesn't recurse into that dict; it only returns the memory used by the class object itself, not including objects that you can reach via the class and its attributes.


Each method is a class attribute. Without going too much into the descriptor protocol, in general, something like foo.why_does_this_not_use_take_memory is really just shorthand for

Foo.why_does_this_not_use_take_memory.__get__(foo, Foo)

That is, the function-valued attribute is retrieved, but then its __get__ method is called to return a method object specific to foo. The method is essentially just a wrapper around the function which, when called, passes foo and its own arguments to Foo.why_does_this_not_use_take_memory (which is how self gets bound to foo).

Upvotes: 6

Related Questions