12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

Why You Will Care: Operator OverloadingLater, we’ll see that objects we implement with classes can pick and choose from thesecategories arbitrarily. For instance, if you want to provide a new kind of specializedsequence object that is consistent with built-in sequences, code a class that overloadsthings like indexing and concatenation:class MySequence:def _ _getitem_ _(self, index):# Called on self[index], othersdef _ _add_ _(self, other):# Called on self + otherand so on. You can also make the new object mutable or not by selectively implementingmethods called for in-place change operations (e.g., _ _setitem_ _ is called onself[index]=value assignments). Although it’s beyond this book’s scope, it’s also possibleto implement new objects in an external language like C as C extension types. Forthese, you fill in C function pointer slots to choose between number, sequence, andmapping operation sets.Table 9-3. Object classificationsObject type Category Mutable?Numbers Numeric NoStrings Sequence NoLists Sequence YesDictionaries Mapping YesTuples Sequence NoFiles Extension N/AObject FlexibilityThis part of the book introduced a number of compound object types (collectionswith components). In general:• Lists, dictionaries, and tuples can hold any kind of object.• Lists, dictionaries, and tuples can be arbitrarily nested.• Lists and dictionaries can dynamically grow and shrink.Because they support arbitrary structures, <strong>Python</strong>’s compound object types are goodat representing complex information in programs. For example, values in dictionariesmay be lists, which may contain tuples, which may contain dictionaries, and soon. The nesting can be as deep as needed to model the data to be processed.Object Flexibility | 183

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

Saved successfully!

Ooh no, something went wrong!