WHAT IS OBJECTS AND DYNAMIC TYPING AND HOW TO USE IN PYTHON PROGRAMMING

OBJECTS AND DYNAMIC TYPING

Values such as 7 (an integer), 4.1 (a floating­point number) and 'dog' are all objects. Every object has a type and a value:

In [1]: type(7)
Out[1]: int
In [2]: type(4.1)
Out[2]: float
In [3]: type('dog')
Out[3]: str

An object’s value is the data stored in the object. The snippets above show objects of built­in types int (for integers), float (for floating-­point numbers) and str (for strings).

Variables Refer to Objects

Assigning an object to a variable binds (associates) that variable’s name to the object. As you’ve seen, you can then use the variable in your code to access the object’s value:

In [4]: x = 7
In [5]: x + 10
Out[5]: 17
In [6]: x
Out[6]: 7

After snippet [4]’s assignment, the variable x refers to the integer object containing 7. As shown in snippet [6], snippet [5] does not change x’s value. You can change x as follows:

In [7]: x = x + 10
In [8]: x
Out[8]: 17

Dynamic Typing

Python uses dynamic typing—it determines the type of the object a variable refers to while executing your code. We can show this by rebinding the variable x to different objects and checking their types:

In [9]: type(x)
Out[9]: int
In [10]: x = 4.1
In [11]: type(x)
Out[11]: float
In [12]: x = 'dog'
In [13]: type(x)
Out[13]: str

Garbage Collection

Python creates objects in memory and removes them from memory as necessary. After snippet [10], the variable x now refers to a float object. The integer object from snippet [7] is no longer bound to a variable. As we’ll discuss in a later chapter, Python automatically removes such objects from memory. This process—called garbage collection—helps ensure that memory is available for new objects you create.

*

Post a Comment (0)
Previous Post Next Post