An object, mutable, immutable

Everything in Python is an object!

What exactly happens when an instruction such as weight = 60 is entered in a Python module?
1) An object is being created. It gets an id, the type is set to int (integer) and the value is set to 60.
2) A name weight is placed in the global namespace, pointing to this object.

Diagram below is an illustration of the above.

Now, lets take a look at mutable and immutable?
An object is called mutable if its value can be changed after it is created.

Consider running the following instructions:

>>>  weight = 60       #1

>>>  weight

60

>>> weight = 70       #2

>>> weight

70

Was the value of weight changed from 60 to 70?

Answer is NO! Reason being that 60 and 72 were integer numbers, of type int, which is immutable.
In #1, weight is set to point to an int object, whose value is 60.
In #2, weight is set to point to a newly created int object with value 70.
Memory address location of the two  int objects are different.

Next, lets have a look at an example of a mutable object.

>>> class Person():

…        def __init__(self, weight):

…       self.weight =  weight

>>> alan = Person(weight=60)

>> >alan.weight

60

>>> id(alan)                           #1

4492989507

>>> id(alan.weight)           #2

4488664279

>>> alan.weight = 65

>>> id(alan)                           #3

4492989507

>>> id(alan.weight)           #4

4488663735

As illustrated above, output from #1 and #3 are showing the same ID, while #2 and #4 are different.

alan is an object whose type is Person (a custom class).
ID of alan is not changed (as per #1 and #3) while the ID of weight has changed (as in #2 and #4).
Custom objects in Python are mutable unless it is coded not to be.

 

About CK Sim

A hands-on, self-motivated professional with over 15 years of experience in embedded system development (hardware and firmware), with project management experience in full product development cycle (design to production). Passionate about Technology, continually enhance and expand knowledge to include IoT, Web Technologies, CyberSecurity and AI.

View all posts by CK Sim →