2

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?

2
  • 3
    Since the class itself is an object and declared at runtime, you do need some memory to hold the class itself…!? Commented Jul 1, 2019 at 7:24
  • @deceze uhem. Please post an answer with more details and references on this topic, so that I could be marked as answer. Commented Jul 1, 2019 at 7:39

1 Answer 1

5

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):
        self.bar = 42

is only a shortcut for this:

def __init__(self):
    self.bar = 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I'd really appreciate if you provide your answer with some links and resources.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.