Mutable, Immutable… everything is object!
Introduction
Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects. In python, everything is an object.
Some peculiarities of OOP in Python are the following:
- Everything is an object, including types and classes.
- Allows multiple inheritance.
- There are no private attributes or methods.
- The attributes can be modified directly.
- Allows “monkey patching”.
- Allows “duck typing”.
- Allows operator overloading.
- It allows the creation of new types of data.
Id and Type
Every object has its own type to represent what kind of value it is. You can use the function type() or isinstance()to see the type of data value.
every object has its unique and unchanged identity which is the memory address in the CPython implementation. To see the object identity, you can use the function id().
Mutable object
Mutable objects are objects that its value can be changed after they were created. In Python, list, set, and dict are mutable.
Immutable object
Immutable objects are objects that its value cannot be changed or modified after they were created. In Python, int, float, bool, string, Unicode, tuple are immutable objects.
In the next image we can see some examples of that:
Why does it matter and how differently does Python treat mutable and immutable objects?
- With mutable objects, when his value is modified, the object is still the same and unchanged. This way is easy to adjust something value and “cheap” to change.
- With immutable objects, when its value is modified, python will create a new object with that modified value.
How arguments are passed to functions?
Both mutable and immutable objects are passed by the reference in Python.
- With mutable objects, the value of the object will change after you pass it to the function.
- With immutable objects, the value of the object will be unchanged.
Thanks for reading this blog, have a nice day.