15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

>>> type(foo) # assumes foo instantiated also<br />

<br />

In addition to type(), there is another useful BIF called isinstance(). We cover it more formally in<br />

Chapter 13 (Object-Oriented <strong>Programming</strong>), but here we can introduce it to show you how you can use<br />

it to help determine the type of an object.<br />

Example<br />

We present a script in Example 4.1 that shows how we can use isinstance() and type() in a runtime<br />

environment. We follow with a discussion of the use of type() and how we migrated to using isinstance<br />

() instead for the bulk of the work in this example.<br />

Example 4.1. Checking the Type (typechk.py)<br />

The function displayNumType() takes a numeric argument and uses the type() built-in to<br />

indicate its type (or "not a number," if that is the case).<br />

1 #!/usr/bin/env python<br />

2<br />

3 def displayNumType(num):<br />

4 print num, 'is',<br />

5 if isinstance(num, (int, long, float, complex)):<br />

6 print 'a number of type:', type(num).__name__<br />

7 else:<br />

8 print 'not a number at all!!'<br />

9<br />

10 displayNumType(-69)<br />

11 displayNumType(9999999999999999999999L)<br />

12 displayNumType(98.6)<br />

13 displayNumType(-5.2+1.9j)<br />

14 displayNumType('xxx')<br />

Running typechk.py, we get the following output:<br />

-69 is a number of type: int<br />

9999999999999999999999 is a number of type: long<br />

98.6 is a number of type: float<br />

(-5.2+1.9j) is a number of type: complex<br />

xxx is not a number at all!!<br />

The Evolution of This Example<br />

Original<br />

The same function was defined quite differently in the first edition of this book:

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

Saved successfully!

Ooh no, something went wrong!