Every thing is an object in Python !!

Introduction:

Python is a clear and powerful object-oriented programming language, Uses an elegant syntax, making the programs you write easier to read.

Guido van Rossum has designed the language according to the principle “first-class everything”. He wrote: “One of my goals for Python was to make it so that all objects were “first class.” In other words, “everything” is treated the same way, everything is a class: functions and methods are values just like lists, integers or floats. Each of these are instances of their corresponding classes.

id and type

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

w1 = "salah"

“Every object has an identity, a type and a value.

The identity of an object uniquely identifies where this object is stored in the computer memory. The function “ id() “ return id the number of the object.

id(w1) # 139753732420720

All data in Python is an object, to see the type of object we use type(), in fact there is several datatype in python: int, float, list tuple, set, bool, dict …

type(w1) # <class 'str'>

Equality vs Identity ( ‘ == ’ vs ‘ is ’)

a == b compares the value of a and b.

a is b will compare the identities of a and b. => id(a) == id(b) ??

but be aware that Short strings and small integers [-5, 255] will return True when compared with is, due to the Python machine attempting to use less memory for identical objects.

Mutable objects:

Mutable objects are objects that can be changed. In Python, the only objects that are mutable are lists, sets, and dict. Take a look at this example:

a = [1, 2, 3]
id(a) # 139753732420720
a.append(4) # [1,2,3,4]
id(a) # 139753732420720

in this example we append some element to the list but the id didn’t change.

because the type of the variable is mutable we can change, delete, update to the variable it self.

b = ["salah" , "wael", "ahmed"]
id(b) # 139753752420945
id(b[0]) # 139753765478812
b[0] = "student"
id(b[0]) # 139753765784269
id(b) # 139753752420945

When we modify a list and change its values in place, the list keeps the same address. However, the address of the value that you changed will have a different address.

Immutable objects:

An immutable object is an object that is not changeable and its state cannot be modified after it is created.

In Python, a string is immutable. You cannot overwrite the values of immutable objects.

However, you can assign the variable again.

In Python, this would include int, float, string, user-defined classes ... These data types cannot be modified. let’s see this exemple:

a = "salah"
a[0] = "T"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

but we need to talk about tuple:

tp = ("student", [4, 5, 6])

the tp it self its ismutable ( cant replace any element), it doesn’t have any setter (can’t modify its length), the string is immutable ( cant modify it ), but the list is mutable so we an play around its elements and update it.

Why does it matter? How does Python treat mutable and immutable objects?

its important to know the type of the variable so that when sent it as params to any function u want to know it would change the original one or not.

besides immutable objects is so useful when u don’t want any thing to change critical data and use it as const data.

how arguments are passed to functions and what does that imply for mutable and immutable objects

def updateList(b):
print(id(b))
b.append(6)
listt = [3, 4, 5]
print(id(listt)) # 140312184155336
updateList(listt) # 140312184155336
print(listt) # [3, 4, 5, 10]
print(id(listt)) # 140312184155336

The variable b refers to the object . by sending listt to updateList() we just send a ref to the the variable that have the same id and since listt is mutable when we update b (the ref) we updated the original (listt)

but if we dont want to touch the original one we will have to create a copy of the ref we received

def copy_list(b):
return b[:]
a = [1,2,3]
cp = copy_list(a)
print(cp) # [1,2,3]
my_list == new_list
True
my_list is new_list
False

When we use the slice operation [:], it creates a copy of a list and when we return that copy, we are returning the reference to that copy (new object).

def increment(b):
print(id(b))
b += 1

n = 25
print(id(n)) # 140312184155337
increment(n) # 140312184155337
print(n)

if we have n is immutable type when we pass n to increment() we pass a ref to the variable n but since we cant update the immutable objects, when we execute b += 1 we are creating a new object that contain b + 1 and its i the scoop of the function. and the object n is never changed so when we print(n) we get 25

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How StyleDiem increased their conversion rate by 25% with a Tars Chatbot

能在同一個表格,Post兩個Model出去嗎?

The different type of Spark functions (custom transformations, column functions, UDFs)

Smart usage of Swift extensions

Setting up Git with Unity — Part One

Von neumann vs Harvard architecture: Introduction to the computer science

Making Android BLE work: — part 4

Recursive functions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Salah Besbes

Salah Besbes

More from Medium

Python pytest:

Python Tricks for beginners

Python Function

Python pytest: