2.8 Objects and Dynamic Typing

The first chapter introduced the terms classes and objects and in Section 2.2, we discussed variables, values and types. 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 Python 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.

Self Check

  1. (Fill-In) Assigning an object to a variable       the variable’s name to the object.
    Answer: binds.

  2. (True/False) A variable always references the same object.
    Answer: False. You can make an existing variable refer to a different object and even one of a different type.

  3. (IPython Session) What is the type of the expression 7.5 * 3?
    Answer:

    In [1]: type(7.5 * 3)
    Out[1]: float
    
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.32.86