我知道在像 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")
我从图中得到的是,在执行通过声明类的行之后,分配了一些内存(在到达实例化部分之前)!。但是没有明确提到这种行为。 我对吗?这就是正在发生的事情吗?
最佳答案
Python 中的一切都是对象,包括类、函数和模块。 class
、def
和 import
语句都是可执行语句,主要是较低级别 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/