Python3: Mutable, Immutable… everything is object!

In the next few lines, I will explore what it means exactly because everything is an object in python. This short guide is intended to provide a minimum education on how objects are used to represent values ​​in Python, a knowledge that is essential for learning object-oriented programming. In today’s post, I will start with a basic introduction to the objects that are in Python.

Object Type

>>> x = 1

All objects in Python are represented by a generalized structure used to describe and access a particular value’s information and methods. To determine the type of an object, you can use the built-in method of the same name, type(). Building on the above example, the type of x, which refers to the value 1, is the numeric type int:

>>> x = 2
>>> type(x)
<class 'int'>

If x referred to the string "hello", it would be an instance of the sequence type str:

>>> x = "hello"
>>> type(x)
<class 'str'>

OBJECT IDENTITY

>>> x = 2
>>> id(x)
10105088

The id() method returns the identity of an object, an integer memory address reading memory addresses in hexadecimal format — to achieve this, you can combine the id() and hex() methods.

>>> x = 2
>>> hex(id(x))
'0x9a3100'

addresses may vary from machine to machine.

OBJECT COMPARISON WITH is & ==

>>> x = 56
>>> y = 65
>>> x is y
False

In the above example, x refers to the memory location of an int object 56, while y refers to the separate location of int object 65, thus, the two variables have different identities, and x is y is False. In more Pythonic terms, x is not y:

>>> x is not y
True

Note that the value of an assignment expression is calculated before a new object is attached to a variable. The above is equivalent to using the value of x in an expression assignment for y:

>>> x = 89
>>> y = x + 9
>>> x is y
False

OBJECT INSTANTIATION | IMMUTABLE OBJECTS

>>> x = 56
>>> y = 56
>>> x is y
True

OBJECT INSTANTIATION — MUTABLE OBJECTS