Skip to content

does class declaration statement cause memory allocation in python?

I know that in languages like c++, memory is not allocated until instantiation. Is it the same in python?
I’m reading the How to think like a computer scientist course. In that course, to elaborate this snippet, a weird figure is given:

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")

This Figure is given: enter image description here

What I get from the figure, Is that after the execution passes through the lines of declaring the class, some memory is allocated(before reaching the instantiation part)!. But this behavior is not explicitly mentioned. Am I right? is this what is happening?


Everything in Python is an object, including classes, functions and modules. The class, def and import statements are all executable statements and mostly syntactic sugar for lower level APIs. In the case of classes, they are actually instances of the type class, and this:

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

is only a shortcut for this:

def __init__(self): = 42
Foo = type("Foo", [object], {"__init__": __init__})
del __init__ # clean up the current namespace

So as you can see, there is indeed an instanciation happening at this point.