Chapter 17. Data types as objects

 

This chapter covers

  • Treating types as objects
  • Using types
  • Creating user-defined classes
  • Understanding duck typing
  • Using special method attributes
  • Subclassing built-in types

By now, you’ve learned the basic Python types as well as 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 are determined at runtime, not at compile time. This fact 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 (not just the objects themselves).

17.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 example 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, the function tells you that 5 is an int (integer) and that ['hello', 'goodbye'] is a list—things that you probably already knew.

Of greater interest is the fact 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)? You have an easy way of finding out. Just use type on that result:

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

17.2. Using types

17.3. Types and user-defined classes

17.4. Duck typing

17.5. What is a special method attribute?

17.6. Making an object behave like a list

17.7. The __getitem__ special method attribute

17.8. Giving an object full list capability

17.9. Subclassing from built-in types

17.10. When to use special method attributes

Summary

sitemap