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.

13.16. Advanced Features of New-Style Classes (<strong>Python</strong> 2.2+)<br />

13.16.1. General Features of New-Style Classes<br />

We have already discussed some of the features tied to new-style classes. With the unification of types<br />

and classes, the most significant of these features is the ability to subclass <strong>Python</strong> data types. One side<br />

effect of this is that all of the <strong>Python</strong> "casting" or conversion built-in functions are now factory functions.<br />

When you call them, you are really instantiating an instance of the corresponding type.<br />

The following built-in function, which have been around <strong>Python</strong> for a while, have been quietly (or<br />

perhaps not) converted to factory functions:<br />

● int(), long(), float(), complex()<br />

● str(), unicode()<br />

● list(), tuple()<br />

● type()<br />

In addition, several new ones have been added to round out the posse:<br />

● basestring() [1]<br />

● dict()<br />

● bool()<br />

[1] New in <strong>Python</strong> 2.3.<br />

● set(), [2] frozenset() [2]<br />

[2] New in <strong>Python</strong> 2.4.<br />

● object()<br />

● classmethod()<br />

● staticmethod()<br />

● super()<br />

● property()<br />

● file()<br />

These class names and factory functions have flexible usage. In addition to creating new objects of<br />

those types, they can be used as base classes when subclassing types, and they can now be used with<br />

the isinstance() built-in function. Using isinstance() can help replace tired old idioms with one that<br />

requires fewer functions calls resulting in cleaner code. For example, to test if an object is an integer,<br />

we had to call type() twice or import the types module and use its attributes; but now we can just use<br />

isinstance() and even gain in performance:

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

Saved successfully!

Ooh no, something went wrong!