Overriding a Built-In Method
Credit: Dave Haynes
Problem
You need to wrap (or, in Python 2.2,
inherit from) a list or tuple, delegating several operations to it,
and want to provide proper slicing (i.e., through the special method
_ _getitem_ _).
Solution
In most cases, overriding special methods of built-in objects when
you inherit from those objects (or wrap them with automatic
delegation, which is not technically an override) poses no special
challenge. When
inheriting in Python 2.2, you can call the
special method of the superclass with the usual unbound-method
syntax. When wrapping, use the syntax that is specific to the
operation, such as self.data[someindex] for
indexing.
Slicing
is harder, because while slicing should go through the same special
method _ _getitem_ _ as indexing (since Python
2.0), lists and tuples still implement an older approach: the more
limited special method _ _getslice_ _ (and
similarly for _ _setitem_ _ versus _ _setslice_ _ and _ _delitem_ _ versus
_ _delslice_ _). So, you must provide a remedy,
normally with a try/except:
class SliceTester:
def _ _init_ _(self):
self.data = ['zero', 'one', 'two', 'three', 'four']
def _ _getitem_ _(self, indexOrSlice):
try:
return self.data[indexOrSlice]
except TypeError:
return self.data[indexOrSlice.start:indexOrSlice.stop]Discussion
When a user-defined class wraps (or, in Python 2.2, inherits from) a
list or tuple, it often needs to define the _ _set*_ _ and _ _get*_ _ special methods and delegate part or all of their ...