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

2024-09-28 18:46:09 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能告诉我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"

当我保存这个类并运行一些与这个类相关的代码时,PVM或Python解释器如何存储类变量、类/静态函数和实例变量?我曾经是一个C++程序员。我想知道这些“东西”存储在哪里(我知道Python只使用堆)?它们什么时候存储,运行时还是运行前?在

例如,我在初始化此类之后运行以下代码:

^{pr2}$

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


Tags: 内存代码selfreturnobjectinitdeftemplate
1条回答
网友
1楼 · 发布于 2024-09-28 18:46:09

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

类对象是在运行时创建的,它具有从属性名到对象的映射,其中在类主体中定义的所有名称都只是属性。这些对象的大多数实现了descriptor protocol(例外是class_purpose属性)。构成大多数属性的函数对象也是在运行时创建的;编译器生成的所有对象都是存储字节码的代码对象,一些常量(由代码创建的任何不可变的东西,包括嵌套作用域的更多代码对象)。在

请参阅datamodel reference documentation,了解这些对象如何相互关联的详细信息。在

绝大多数Python开发人员不必担心内存管理。如果您是针对Python C API开发的,您可能需要阅读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.

相关问题 更多 >