mirror of
https://gitea.com/Lerking/python-crash-course.git
synced 2025-07-21 07:31:04 +02:00
60 lines
2.3 KiB
Python
60 lines
2.3 KiB
Python
"""
|
|
Mutable and immutable objects
|
|
"""
|
|
|
|
# A mutable object is an object which can be modified in place.
|
|
# In python, everything is an object(class). So creating any variable
|
|
# will create a class instance of that object type, with a specific set of methods,
|
|
# which can operate on the object. It will also contain the content.
|
|
#
|
|
# A mutable object is an object which stays the same object, no matter what legal operation you do on it.
|
|
# There are basically 3 types of mutable objects in python.
|
|
# Lists, dictionaries and sets.
|
|
list()
|
|
dict()
|
|
set()
|
|
|
|
# What makes these objects mutable, is the fact that you can alter the content without
|
|
# altering the object itself. i.e. you can append items to a list or remove items from a list.
|
|
# The same mechanics are true for dictionaries and sets.
|
|
|
|
# Immutable objects are objects that can't be changed.
|
|
# These are some of the types which are immutable.
|
|
str()
|
|
int()
|
|
float()
|
|
|
|
# What characterisses an immutable object, is that the object itself holds the content.
|
|
# In other words, 1 value = 1 object. Take the following example.
|
|
A: int = 5
|
|
B: int = 5
|
|
|
|
# Here, we have created 2 objects 'A' and 'B', both with the integer value '5'.
|
|
# What happens in python is that when creating such objects, it will start by searching
|
|
# already created objects to see if an object with this specific value has already been
|
|
# created. If python finds that an object of this particular type and value exists, it
|
|
# will return a pointer to this object.
|
|
# That means that in our example, both 'A' and 'B' are the same object. We can prove that
|
|
# with the following. Using id() on the variable(class object) will show the internal
|
|
# python id of that object.
|
|
print(id(A))
|
|
print(id(B))
|
|
|
|
# So we can see that these objects both points to the same internal object, meaning that
|
|
# only 1 int(5) object exists, but we can have multiple varables pointing to it.
|
|
# This is exactly what immutable objects are. There can be only 1 of each.
|
|
# Now explore the following.
|
|
A: int = 5
|
|
B: int = 5
|
|
print(id(A))
|
|
print(id(B))
|
|
B += 1 # add 1 to variable 'B'
|
|
print(id(A))
|
|
print(id(B))
|
|
|
|
# What happens here?
|
|
# Now variable 'A' still points to the int(5) class object. But a new int(6) clas object
|
|
# have been created and variable 'B' now points to this object.
|
|
# The same is the case with string objects. Each string object can only contain the string
|
|
# value, it was created with.
|