15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4.3. Other Built-in Types<br />

● Type<br />

● Null object (None)<br />

● File<br />

● Set/Frozenset<br />

● Function/Method<br />

● Module<br />

● Class<br />

These are some of the other types you will interact with as you develop as a <strong>Python</strong> programmer. We<br />

will also cover all of these in other chapters of this book with the exception of the type and None types,<br />

which we will discuss here.<br />

4.3.1. Type Objects and the type Type Object<br />

It may seem unusual to regard types themselves as objects since we are attempting to just describe all<br />

of <strong>Python</strong>'s types to you in this chapter. However, if you keep in mind that an object's set of inherent<br />

behaviors and characteristics (such as supported operators and built-in methods) must be defined<br />

somewhere, an object's type is a logical place for this information. The amount of information necessary<br />

to describe a type cannot fit into a single string; therefore types cannot simply be strings, nor should<br />

this information be stored with the data, so we are back to types as objects.<br />

We will formally introduce the type() BIF below, but for now, we want to let you know that you can find<br />

out the type of an object by calling type() with that object:<br />

>>> type(42)<br />

<br />

Let us look at this example more carefully. It does not look tricky by any means, but examine the return<br />

value of the call. We get the seemingly innocent output of , but what you need to realize is<br />

that this is not just a simple string telling you that 42 is an integer. What you see as is<br />

actually a type object. It just so happens that the string representation chosen by its implementors has<br />

a string inside it to let you know that it is an int type object.<br />

Now you may ask yourself, so then what is the type of any type object? Well, let us find out:<br />

>>> type(type(42))<br />

<br />

Yes, the type of all type objects is type. The type type object is also the mother of all types and is the<br />

default metaclass for all standard <strong>Python</strong> classes. It is perfectly fine if you do not understand this now.<br />

This will make sense as we learn more about classes and types.<br />

With the unification of types and classes in <strong>Python</strong> 2.2, type objects are playing a more significant role<br />

in both object-oriented programming as well as day-to-day object usage. Classes are now types, and<br />

instances are now objects of their respective types.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!