Python 解释器如何为不同的方法分配内存?

How does Python interpreter allocate memory for different methods?

谁能告诉我 Python 解释器或 PVM 如何管理以下代码的内存?

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

    @classmethod
    def getPurpose(cls):
        return cls.class_purpose

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

当我保存此 class 和 运行 一些与此 class 相关的代码时,PVM 或 Python 解释器如何存储 class 变量,class/static函数和实例变量?我曾经是一名 C++ 程序员。我想知道那些 "things" 存储在哪里(我知道 Python 只使用堆)?它们何时存储,运行时还是运行时之前?

例如,我 运行 初始化此代码后 class:

a = A()
a.getParams()
A.getPurpose()
A.printout()

Python 解释器如何在这段代码后面分配内存?

您示例中的所有内容都只是一个对象。所有对象都在堆上。

class 对象是在运行时创建的,具有从属性名称到对象的映射,其中您在 class 正文中定义的所有名称都只是属性。这些对象中的大多数都实现了 descriptor protocolclass_purpose 属性除外)。构成大部分属性的函数对象也是在运行时创建的;所有编译器生成的都是存储字节码的代码对象,一些常量(代码创建的任何不可变的东西,包括用于嵌套范围的更多代码对象)。

有关这些对象如何相互关联的更多详细信息,请参阅 datamodel reference documentation

绝大多数 Python 开发人员不必担心内存管理。如果您针对 Python C API, you may want to read up on the Memory Management section 进行开发,它会声明:

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.