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 ...
Get Programming Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.