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

标签 python class

我知道在像 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/

相关文章:

javascript - 无法在自己的类中调用静态函数

python - 在 IPython Notebook 中自动运行 %matplotlib inline

python - 远程机器人 : how to retrieve InlineKeyboardButton callback data?

python - 如何在Python中找到循环中图的所有交点?

python - 打印带条件的二次方程

iphone - 我怎样才能在iPhone中将一个类的值赋予另一个类?

python - 如何在 Python3 中使用构造函数模拟对象?

python - 在 Python 中打开一个 wave 文件 : unknown format: 49. 出了什么问题?

jquery - 与 jQuery 选择器一起使用的 CSS 类命名的最佳实践

python - 为什么在 Python 中没有从对象的方法中引用对象成员的简写?