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

(yzsuai) #1

Project
Extract named fields from the tuples in a table.


Difference
Remove one set’s tuples from another.


These operations go beyond the tools provided by Python’s built-in set object, and are
a prime example of why you may wish to implement a custom set type in the first place.
Although I have ported this code to run under Python 3.X, I have not revisited it in any
sort of depth for this edition, because today I would probably prefer to implement it
as a subclass of the built-in set type, rather than a part of a proprietary set implemen-
tation. Coincidentally, that leads us to our next topic.


Subclassing Built-in Types


Before we move on to other classical data structures, there is one more twist in the stack
and set story. 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 are
now themselves customizable classes, we can code unique datatypes that are extensions
of built-ins, with subclasses that inherit built-in tool sets. This is especially true in
Python 3.X, where “type” and “class” have become veritable synonyms altogether.


To demonstrate, Example 18-13 shows the main parts of a module containing variants
of our stack and set objects coded in the prior sections, revised as customized lists. For
variety, the set union method has also been simplified slightly here to remove a redun-
dant loop.


Example 18-13. PP4E\Dstruct\Basic\typesubclass.py


"customize built-in types to extend, instead of starting from scratch"


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)


Subclassing Built-in Types| 1383
Free download pdf