gpt4 book ai didi

python - 类声明语句会导致python中的内存分配吗?

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:46 25 4
gpt4 key购买 nike

我知道在像 c++ 这样的语言中,直到 instantiation 才会分配内存。在python中也是一样吗?
我正在阅读 How to think like a computer scientist类(class)。在那个类(class)中,为了详细说明这个片段,给出了一个奇怪的数字:

class Point:
""" Point class for representing and manipulating x,y coordinates. """

def __init__(self):
""" Create a new point at the origin """
self.x = 0
self.y = 0

p = Point() # Instantiate an object of type Point
q = Point() # and make a second point

print("Nothing seems to have happened with the points")

此图给出: enter image description here

我从图中得到的是,在执行通过声明类的行之后,分配了一些内存(在到达实例化部分之前)!。但是没有明确提到这种行为。我对吗?这就是正在发生的事情吗?

最佳答案

Python 中的一切都是对象,包括类、函数和模块。 classdefimport 语句都是可执行语句,主要是较低级别 API 的语法糖。对于类,它们实际上是 type 类的实例,并且:

class Foo(object):
def __init__(self):
self.bar = 42

只是一个捷径:

def __init__(self):
self.bar = 42

Foo = type("Foo", [object], {"__init__": __init__})

del __init__ # clean up the current namespace

如您所见,此时确实发生了实例化。

关于python - 类声明语句会导致python中的内存分配吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831476/

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