Read my book

I wrote books about Webpack and React. Check them out!

Sunday, June 7, 2009

Subclassing a list in Python

Sometimes you need to data types provided with Python. You can do a lot of neat stuff just by subclassing and then adding some own tweaks to the child class. Here's an example:

Additionally you can override the default functionality (ie. __getitem__, __setitem__, __call__ etc.). Note that to refer to the contents of the data structure itself you can use "self". So to iterate the contents of a subclassed dictionary inside its method you can use something like "for k, v in self.items(): ..." and it should work.