O'Reilly logo

Programming Python, 3rd Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Subclassing Built-In Types

There is one more twist in the stack and set story, before we move on to some more classical data structures. In recent Python releases, it is also possible to subclass built-in datatypes such as lists and dictionaries, in order to extend them. That is, because datatypes now look and feel just like customizable classes, we can code unique datatypes that are extensions of built-ins, with subclasses that inherit built-in tool sets. For instance, here are our stack and set objects coded in the prior sections, revised as customized lists (the set union method has been simplified slightly here to remove a redundant loop):

class Stack(list): "a list with extra methods" def top(self): return self[-1] def push(self, item): list.append(self, item) def pop(self): if not self: return None # avoid exception else: return list.pop(self) class Set(list): " a list with extra methods and operators" def _ _init_ _(self, value=[]): # on object creation list._ _init_ _(self) self.concat(value) def intersect(self, other): # other is any sequence type res = [] # self is the instance subject for x in self: if x in other: res.append(x) return Set(res) # return a new Set def union(self, other): res = Set(self) # new set with a copy of my list res.concat(other) # insert uniques from other return res def concat(self, value): # value: a list, string, Set... for x in value: # filters out duplicates if not x in self: self.append(x) # len, getitem, iter inherited, use list repr def ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required