[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

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 and(self, other): return self.intersect(other)
def or(self, other): return self.union(other)
def str(self): return '<Set:' + repr(self) + '>'


class FastSet(dict):
pass # this doesn't simplify much


...self-test code omitted: see examples package file...


The stack and set implemented in this code are essentially like those we saw earlier,
but instead of embedding and managing a list, these objects really are customized lists.
They add a few additional methods, but they inherit all of the list object’s functionality.


This can reduce the amount of wrapper code required, but it can also expose func-
tionality that might not be appropriate in some cases. As coded, for example, we’re
able to sort and insert into stacks and reverse a set, because we’ve inherited these
methods from the built-in list object. In most cases, such operations don’t make sense
for these data structures, and barring extra code that disables such nonfeatures, the
wrapper class approach of the prior sections may still be preferred.


For more on the class subtype classes, see the remainder of their implementation file
in the examples package for self-test code and its expected output. Because these objects
are used in the same way as our original stacks and sets, interacting with them is left
as suggested exercise here.


Subclassing built-in types has other applications, which may be more useful than those
demonstrated by the preceding code. Consider a queue, or ordered dictionary, for ex-
ample. The queue could take the form of a list subclass with get and put methods to
insert on one end and delete from the other; the dictionary could be coded as a dic-
tionary subclass with an extra list of keys that is sorted on insertion or request. While
this scheme works well for types that resemble built-ins, though, type subclasses may


1384 | Chapter 18: Data Structures

Free download pdf