Chapter 19. Data types as objects

 

This chapter covers

  • Treating types as objects
  • Using types
  • Creating user-defined classes
  • Understanding duck typing

By now, you’ve learned the basic Python types and also how to create your own data types using classes. For many languages, that would be pretty much it, as far as data types are concerned. But Python is dynamically typed, meaning that types of things are determined at runtime, not at compile time. This is one of the reasons Python is so easy to use. It also makes it possible, and sometimes necessary, to compute with the types of objects (and not just the objects themselves).

19.1. Types are objects, too

Fire up a Python session, and try out the following:

>>> type(5)
<class 'int'>
>>> type(['hello', 'goodbye'])
<class 'list'>

This is the first time you’ve seen the built-in type function in Python. It can be applied to any Python object and returns the type of that object. In this example, it tells us that 5 is an int (integer) and that ['hello', 'goodbye'] is a list, something you probably already knew.

Of greater interest is that Python returns objects in response to the calls to type; <class 'int'> and <class 'list'> are the screen representations of the returned objects. What sort of object is returned by a call of type(5)? We have any easy way of finding out—just use type on that result:

>>> type_result = type(5)
>>> type(type_result)
<class 'type'>

19.2. Using types

19.3. Types and user-defined classes

19.4. Duck typing

19.5. Summary