Gauss Lee Gauss Lee - 1 year ago 96
Python Question

How does Python interpreter allocate memory for different methods?

Can anyone tell me how does Python interpreter or PVM manage memories for the following code?

class A(object):
class_purpose = "template"
def __init__(self):
self.a = 0.0
self.b = 0.0

def getParams(self):
return self.a, self.b

def getPurpose(cls):
return cls.class_purpose

def printout():
print "This is class A"

When I save this class and run some codes related to this class, how does PVM or Python interpreter store class variables, class/static functions and instance variables? I used to be a C++ programmer. I wonder where those "things" are stored (I know Python only uses Heap)? When are they stored, RunTime or before RunTime?

For example, I run this code after initing this class:

a = A()

How does Python interpreter allocate memory behind this code?

Answer Source

Everything in your example is simply an object. All objects go on the heap.

The class object is created at runtime and has a mapping from attribute name to objects, where all names you defined in the class body are simply attributes. The majority of those objects implement the descriptor protocol (the exception being the class_purpose attribute). The function objects that form the majority of the attributes are also created at runtime; all the compiler produces are code objects which store bytecode, some constants (anything immutable created by the code, including more code objects for nested scopes).

See the datamodel reference documentation for more details on how these objects relate to one another.

The vast majority of Python developers don't have to worry about memory management. If you develop against the Python C API, you may want to read up on the Memory Management section, which does state:

It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if she regularly manipulates object pointers to memory blocks inside that heap. The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python memory manager through the Python/C API functions listed in this document.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download