Search code examples
pythonclassobjectint

Do the 'int' objects in Python only contain values?


Let's take the following Python code:

a = 3
print(a)

As far as I know, a is a reference to an object of class int — correct me if I am wrong. Diagrammatically, it should look something like this, as far as I know.

    The object of 'int' class
       containing value 3

        |---|
a ----> | 3 |
        |---|

Does the 'int' object in memory only contain the value 3 or it contains some space for other variables as well?

Our professor told us that it looks something like below:

   The object of class 'int'
        |--------|
        |   ___  |
a ----> |   |3|  |
        |   ---  |
        |--------|

So, is the remaining space utilized by some other variables?


Solution

  • Any object in Python inherits from the object class, which means that it's treated as any Python object, not as a primitive value as you'd expect from a language like C. This is what people mean when they say that in Python, everything is an object.

    For example, the int class has a method __str__ that dictates what its string representation looks like:

    >>> a = 3
    >>> a.__str__()
    '3'
    

    You can use dir(a) to get a list of every method associated with a.

    So to answer your question, yes - the int object does not only allocates the space needed for the primitive value itself, but also for the whole Python object associated with it.