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.

B RAINB UILDERPart VI ExercisesThese exercises ask you to write a few classes, and experiment with some existingcode. Of course, the problem with existing code is that it must be existing. To workwith the set class in exercise 5, either pull the class source code off the Internet (seethe Preface), or type it up by hand (it’s fairly brief). These programs are starting toget more sophisticated, so be sure to check the solutions at the end of the book forpointers. You’ll find them in in Appendix B, in “Part VI, Classes and OOP.”1. Inheritance. Write a class called Adder that exports a method add(self, x, y) thatprints a “Not Implemented” message. Then, define two subclasses of Adder thatimplement the add method:ListAdderWith an add method that returns the concatenation of its two list arguments.DictAdderWith an add method that returns a new dictionary containing the items inboth its two dictionary arguments (any definition of addition will do).Experiment by making instances of all three of your classes interactively and callingtheir add methods.Now, extend your Adder superclass to save an object in the instance with a constructor(e.g., assign self.data a list or a dictionary), and overload the + operatorwith an _ _add_ _ method to automatically dispatch to your add methods (e.g.,X+Ytriggers X.add(X.data,Y)). Where is the best place to put the constructorsand operator overloading methods (i.e., in which classes)? What sorts of objectscan you add to your class instances?In practice, you might find it easier to code your add methods to accept just onereal argument (e.g., add(self,y)), and add that one argument to the instance’scurrent data (e.g., self.data + y). Does this make more sense than passing twoarguments to add? Would you say this makes your classes more “objectoriented”?2. Operator overloading. Write a class called Mylist that shadows (“wraps”) a <strong>Python</strong>list: it should overload most list operators and operations, including +, indexing,iteration, slicing, and list methods such as append and sort. See the <strong>Python</strong>reference manual for a list of all possible methods to support. Also, provide a constructorfor your class that takes an existing list (or a Mylist instance) and copiesits components into an instance member. Experiment with your class interactively.Things to explore:a. Why is copying the initial value important here?b. Can you use an empty slice (e.g., start[:]) to copy the initial value if it’s aMylist instance?566 | Chapter 26: Advanced Class Topics

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

Saved successfully!

Ooh no, something went wrong!