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.

This change allows you to customize or extend the behavior of built-in types withuser-defined class statements: simply subclass the new type names to customizethem. Instances of your type subclasses can be used anywhere that the original builtintype can appear. For example, suppose you have trouble getting used to the factthat <strong>Python</strong> list offsets begin at 0 instead of 1. Not to worry—you can always codeyour own subclass that customizes this core behavior of lists. The file typesubclass.pyshows how:# Subclass built-in list type/class.# Map 1..N to 0..N-1; call back to built-in version.class MyList(list):def _ _getitem_ _(self, offset):print '(indexing %s at %s)' % (self, offset)return list._ _getitem_ _(self, offset - 1)if __name__ == '_ _main_ _':print list('abc')x = MyList('abc')print xprint x[1]print x[3]# _ _init_ _ inherited from list# _ _repr_ _ inherited from list# MyList._ _getitem_ _# Customizes list superclass methodx.append('spam'); print xx.reverse( ); print x# Attributes from list superclassIn this file, the MyList subclass extends the built-in list’s _ _getitem_ _ indexingmethod only to map indexes 1 to N back to the required 0 to N–1. All it really doesis decrement the index submitted, and call back to the superclass’ version of indexing,but it’s enough to do the trick:% python typesubclass.py['a', 'b', 'c']['a', 'b', 'c'](indexing ['a', 'b', 'c'] at 1)a(indexing ['a', 'b', 'c'] at 3)c['a', 'b', 'c', 'spam']['spam', 'c', 'b', 'a']This output also includes tracing text the class prints on indexing. Whether changingindexing this way is a good idea in general is another issue—users of your MyListclass may very well be confused by such a core departure from <strong>Python</strong> sequencebehavior. The fact that you can customize built-in types this way can be a powerfultool though, in general.For instance, this coding pattern gives rise to an alternative way to code sets—as asubclass of the built-in list type, rather than a standalone class that manages anembedded list object. The following class, coded in the file setsubclass.py, customizesExtending Built-in Types | 541

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

Saved successfully!

Ooh no, something went wrong!