2.8 Objects and Dynamic Typing

  • 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.
  • Can then use the variable to access the object’s value.
In [4]:
x = 7
In [5]:
x + 10
Out[5]:
17
In [6]:
x
Out[6]:
7
  • Variable x refers to the integer object containing 7.
In [7]:
x = x + 10
In [8]:
x
Out[8]:
17

Dynamic Typing (1 of 2)

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

Dynamic Typing (2 of 2)

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.
  • When an object is no longer bound to a variable, Python can automatically removes the object from memory.
  • This process—called garbage collection—helps ensure that memory is available for new objects.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 2 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.