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>Python</strong>25> python>>> import mypkg.mymodinitializing mypkg>>> mypkg.mymod.countLines('mypkg\mymod.py')13>>> from mypkg.mymod import countChars>>> countChars('mypkg\mymod.py')3466. Reloads. This exercise just asks you to experiment with changing the changer.pyexample in the book, so there’s nothing to show here.7. Circular imports. The short story is that importing recur2 first works because therecursive import then happens at the import in recur1, not at a from in recur2.The long story goes like this: importing recur2 first works because the recursiveimport from recur1 to recur2 fetches recur2 as a whole, instead of getting specificnames. recur2 is incomplete when imported from recur1, but because ituses import instead of from, you’re safe: <strong>Python</strong> finds and returns the already createdrecur2 module object, and continues to run the rest of recur1 without aglitch. When the recur2 import resumes, the second from finds the name Y inrecur1 (it’s been run completely), so no error is reported. Running a file as ascript is not the same as importing it as a module; these cases are the same asrunning the first import or from in the script interactively. For instance, runningrecur1 as a script is the same as importing recur2 interactively, as recur2 is thefirst module imported in recur1.Part VI, Classes and OOPSee “Part VI Exercises” in Chapter 26 for the exercises.1. Inheritance. Here’s the solution code for this exercise (file adder.py), along withsome interactive tests. The _ _add_ _ overload has to appear only once, in thesuperclass, as it invokes type-specific add methods in subclasses:class Adder:def add(self, x, y):print 'not implemented!'def _ _init_ _(self, start=[]):self.data = startdef _ _add_ _(self, other):return self.add(self.data, other)class ListAdder(Adder):def add(self, x, y):return x + yclass DictAdder(Adder):def add(self, x, y):new = {}for k in x.keys( ): new[k] = x[k]for k in y.keys( ): new[k] = y[k]return new664 | Appendix B: Solutions to End-of-Part Exercises# Or in subclasses?# Or return type?

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

Saved successfully!

Ooh no, something went wrong!