Python 3: Mutable, Immutable... everything is an object!
https://www.youtube.com/watch?v=d-aYRlbEbBw

Python 3: Mutable, Immutable... everything is an object!

Introduction:

Yesterday, at Holberton, we did a project ( in python) that explained some important deep concepts about how does Python works under the hood, so now I'll try to explain the most important ones.

Id function:

The id() function returns identity (unique integer) of an object. It receives an object and outputs its identity.

This is an example:

Input:
print('id of 5 =',id(5))
a = 
print('id of a =',id(a))

Output:
id of 5 = 140472391630016
id of a = 140472391630016        

It's important to note that everything in Python is an object, even numbers, and Classes.

As you can see above, integer?5?has a unique id. The id of the integer?5?remains the same. This is similar to how c works.

Type function:

The?type()?function returns the type of the object passed.

This is an example:

numbers = [1, 2, 3, 4]
result = type(numbers)
print(result)
Output: class list        

If several types are passed, it returns every type.

Which objects are mutable and immutable?

No hay texto alternativo para esta imagen

And now, what makes an object mutable or not?

Mutable objects:

A mutable object can change its state or contents whereas immutable objects cannot.

Mutable objects are exceptional to use when you need to change the size of the object, for example list, dict etc.

Immutable Objets:

Immutable objects are objects which, can not be changed or mutable but using nonefficient ways such as creating a copy. The main difference is that when a new object is created, a new Id will be assigned to the object. Whereas Immutable objects will keep the same ID unless their value is changed.

Passing Arguments to Functions, Mutable and Immutable Objects:

These diferences among objects, also conclude into different ways to pass them to functions.

Memory efficiency is highly damaged when not taking these differences into account.

For example if a mutable object is called by reference in a function, it can change the original variable itself. So to avoid this, the original variable needs to be copied to another variable as mentioned before. Immutable objects can be called by reference because their value cannot be changed anyways.









要查看或添加评论,请登录

Juan Giménez的更多文章

社区洞察

其他会员也浏览了