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.

9. The Dead Parrot Sketch. Here’s how I implemented this one (file parrot.py).Notice how the line method in the Actor superclass works: by accessing selfattributes twice, it sends <strong>Python</strong> back to the instance twice, and hence invokestwo inheritance searches—self.name and self.says( ) find information in thespecific subclasses:class Actor:def line(self): print self.name + ':', repr(self.says( ))class Customer(Actor):name = 'customer'def says(self): return "that's one ex-bird!"class Clerk(Actor):name = 'clerk'def says(self): return "no it isn't..."class Parrot(Actor):name = 'parrot'def says(self): return Noneclass Scene:def _ _init_ _(self):self.clerk = Clerk( ) # Embed some instancesself.customer = Customer( )# Scene is a compositeself.subject = Parrot( )def action(self):self.customer.line( )self.clerk.line( )self.subject.line( )# Delegate to embeddedPart VII, Exceptions and ToolsSee “Part VII Exercises” in Chapter 29 for the exercises.1. try/except. My version of the oops function (file oops.py) follows. As for thenoncoding questions, changing oops to raise a KeyError instead of an IndexErrormeans that the try handler won’t catch the exception (it “percolates” to the toplevel, and triggers <strong>Python</strong>’s default error message). The names KeyError andIndexError come from the outermost built-in names scope. Import _ _builtin_ _,and pass it as an argument to the dir function to see for yourself:def oops( ):raise IndexErrordef doomed( ):try:oops( )except IndexError:print 'caught an index error!'else:print 'no error caught...'672 | Appendix B: Solutions to End-of-Part Exercises

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

Saved successfully!

Ooh no, something went wrong!