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.

As we learned earlier, the _ _repr_ _ operator overloading method used here is calledfor printing and for string conversion requests made to your class’ instances; _ _str_ _defines the user-friendly display preferred by print statements. (See “Operator Overloading”in Chapter 24 for more on display-string methods.)Note that if we inherit from built-in exception classes, as recommended earlier, theerror test is modified slightly—constructor arguments are automatically saved anddisplayed in the message:>>> class MyBad(Exception): pass>>> raise MyBad( )Traceback (most recent call last):File "", line 1, in raise MyBad( )MyBad>>> class MyBad(Exception): pass>>> raise MyBad('the', 'bright', 'side', 'of', 'life')Traceback (most recent call last):File "", line 1, in raise MyBad('the', 'bright', 'side', 'of', 'life')MyBad: ('the', 'bright', 'side', 'of', 'life')If your end users might see exception error messages, you will probably want todefine your own custom display format methods with operator overloading, asshown here. Being able to automatically attach state information to instances likethis, though, is a generally useful feature, as the next section explores.Sending Extra Data and Behavior in InstancesBesides supporting flexible hierarchies, class exceptions also provide storage for extrastate information as instance attributes. When a class-based exception is raised,<strong>Python</strong> automatically passes the class instance object along with the exception as theextra data item. As for string exceptions, you can access the raised instance by listingan extra variable back in the try statement. This provides a natural hook for supplyingdata and behavior to the handler.Example: Extra data with classes and stringsLet’s explore the notion of passing extra data with an example, and compare thestring- and class-based approaches along the way. A program that parses data filesmight signal a formatting error by raising an exception instance that is filled out withextra details about the error:>>> class FormatError:... def _ _init_ _(self, line, file):... self.line = line... self.file = file...Class-Based Exceptions | 611

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

Saved successfully!

Ooh no, something went wrong!