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.

c. <strong>Is</strong> there a general way to route list method calls to the wrapped list?d. Can you add a Mylist and a regular list? How about a list and a Mylistinstance?e. What type of object should operations like + and slicing return? What aboutindexing operations?f. If you are working with a more recent <strong>Python</strong> release (version 2.2 or later),you may implement this sort of wrapper class by embedding a real list in astandalone class, or by extending the built-in list type with a subclass.Which is easier, and why?3. Subclassing. Make a subclass of Mylist from exercise 2 called MylistSub, whichextends Mylist to print a message to stdout before each overloaded operation iscalled, and counts the number of calls. MylistSub should inherit basic methodbehavior from Mylist. Adding a sequence to a MylistSub should print a message,increment the counter for + calls, and perform the superclass’ method. Also,introduce a new method that prints the operation counters to stdout, and experimentwith your class interactively. Do your counters count calls per instance, orper class (for all instances of the class)? How would you program both of these?(Hint: it depends on which object the count members are assigned to: classmembers are shared by instances, but self members are per-instance data.)4. Metaclass methods. Write a class called Meta with methods that intercept everyattribute qualification (both fetches and assignments), and print messages listingtheir arguments to stdout. Create a Meta instance, and experiment withqualifying it interactively. What happens when you try to use the instance inexpressions? Try adding, indexing, and slicing the instance of your class.5. Set objects. Experiment with the set class described in “Extending Types byEmbedding.” Run commands to do the following sorts of operations:a. Create two sets of integers, and compute their intersection and union byusing & and | operator expressions.b. Create a set from a string, and experiment with indexing your set. Whichmethods in the class are called?c. Try iterating through the items in your string set using a for loop. Whichmethods run this time?d. Try computing the intersection and union of your string set, and a simple<strong>Python</strong> string. Does it work?e. Now, extend your set by subclassing to handle arbitrarily many operandsusing the *args argument form. (Hint: see the function versions of thesealgorithms in Chapter 16.) Compute intersections and unions of multipleoperands with your set subclass. How can you intersect three or more sets,given that & has only two sides?Part VI Exercises | 567

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

Saved successfully!

Ooh no, something went wrong!