All types in Python are objects !

The Python data model is a little confusing for newcomers who use other languages.
The first sentence says:

Objects are Python’s abstraction for data
All data in a Python program is represented by objects or by relations between objects

And does not explain it clearly.
Are simple numbers also considered objects ?

primitive types/reference types

Java defines “primitive types” defined in the language core.
C and C++ defines just variable types.
A variable that is defined with one if these types “contains” the value inside. Notice the following note from a tutorial in the Oracle site:
“Primitive values do not share state with other primitive values.”
Here, “state” means the value contained inside the variable.
So if we store the number 5 in an integer type variable, we could later store another number inside the same location.
This is not the case with Python, where the int type is immutable, and cannot change.

Python does not have primitive types !!!
All data in Python is stored in objects.

The data model of the language reference says:

Every object has an identity, a type and a value.
An object’s identity never changes once it has been created.
…the id() function returns an integer representing its identity.

For example:

Notes:

The name a is attached to an immutable object of the type int.
The name b is attached to this same object.
The numbers output by id() function identify this object

What happen if we add another assignment ?

The assignment to a variable that references an immutable object will create a new object, with the value 5.
The name a will reference the new object (that has a new id)
The name b will keep referencing the old object.

So, we can sum it up:
Python variables are just names that reference an object.

 


Leave a Reply

Your email address will not be published. Required fields are marked *