12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Extending Types by EmbeddingRemember those set functions we wrote in Part IV? Here’s what they look likebrought back to life as a <strong>Python</strong> class. The following example (the file setwrapper.py)implements a new set object type by moving some of the set functions to methods,and adding some basic operator overloading. For the most part, this class just wrapsa <strong>Python</strong> list with extra set operations. Because it’s a class, it also supports multipleinstances and customization by inheritance in subclasses:class Set:def _ _init_ _(self, value = []):self.data = []self.concat(value)# Constructor# Manages a listdef intersect(self, other):res = []for x in self.data:if x in other:res.append(x)return Set(res)def union(self, other):res = self.data[:]for x in other:if not x in res:res.append(x)return Set(res)def concat(self, value):for x in value:if not x in self.data:self.data.append(x)# other is any sequence# self is the subject# Pick common items# Return a new Set# other is any sequence# Copy of my list# Add items in other# value: list, Set...# Removes duplicatesdef _ _len_ _(self): return len(self.data) # len(self)def _ _getitem_ _(self, key): return self.data[key] # self[i]def _ _and_ _(self, other): return self.intersect(other) # self & otherdef _ _or_ _(self, other): return self.union(other) # self | otherdef _ _repr_ _(self): return 'Set:' + `self.data` # PrintOverloading indexing enables instances of our Set class to masquerade as real lists.Because you will interact with and extend this class in an exercise at the end of thischapter, I won’t say much more about this code until Appendix B.Extending Types by SubclassingBeginning with <strong>Python</strong> 2.2, all the built-in types can now be subclassed directly.Type-conversion functions such as list, str, dict, and tuple have become built-intype names—although transparent to your script, a type-conversion call (e.g.,list('spam')) is now really an invocation of a type’s object constructor.540 | Chapter 26: Advanced Class Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!