gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:59 24 4
gpt4 key购买 nike

谁能告诉我 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 只使用堆)?它们何时存储,运行时还是运行时之前?

例如,我在初始化这个类后运行这段代码:

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

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

最佳答案

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

类对象是在运行时创建的,具有从属性名称到对象的映射,您在类主体中定义的所有名称都只是属性。这些对象中的大多数都实现了 descriptor protocol (异常(exception)是 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.

关于python - Python 解释器如何为不同的方法分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com