Everything is object! Mutable and Immutable... in Python3

Everything is object! Mutable and Immutable... in Python3

Introduction:

Hello reader, in OOP (Object-oriented Programming), everything is an object... Hence the name.. OBJECT-oriented. Duh! Thanks for reading.

Jokes aside, what is Object-oriented Programming?

Object-oriented programming is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior.

Each object has its own id and type.

Why use OOP?

The organization of an object-oriented program also makes the method beneficial to collaborative development, where projects are divided into groups. Additional benefits of OOP include code reusability, scalability and efficiency.

What is an ID and Type?

The id is the memory address in the CPython implementation, for example we have a variable called 'a' if we assign data to it, it will have a memory address, this memory address is an id we can see this using the built-in id() function in Python3.

No alt text provided for this image



The type is the data type of our variable, like the above example, we gave the 'a' variable the 'str' data type because we have assigned a String to it, we will be using the variable 'b' to showcase the type using the type() function in Python3.

No alt text provided for this image



Mutable Objects.

What is a Mutable Object?

Mutable Objects are objects where you can change their content without changing their identity.

In example

No alt text provided for this image




we changed the content for my_list, yet the object id is still the same.

Some common mutable objects would be:

? Sequence: list(), bytearray()

? Set type: set()

? Mapping type: dict()

? Classes, Class instances... and much much more

Immutable Objects.

What is an Immutable Object?

On the other hand, Immutable Objects can not change in place.

No alt text provided for this image



Some common immutable objects would be:

? numbers: int(), float(), complex()

? immutable sequences: str(), tuple(), frozenset(), bytes()

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

Below is a clear example of how functions interact with mutable and immutable objects in Python3

x = something # immutable type
print x
func(x)
print x # prints the same thing

x = something # mutable type
print x
func(x)
print x # might print something different

x = something # immutable type
y = x
print x
# some statement that operates on y
print x # prints the same thing

x = something # mutable type
y = x
print x
# some statement that operates on y
print x # might print something differente        

Thanks for reading. For real this time ^^.

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

Youssef Jellouli的更多文章

社区洞察

其他会员也浏览了