04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

554 APPENDIX A ■ THE SHORT VERSION<br />

■Note You can use the special method __del__ to implement destructor behavior, but because you don’t<br />

know exactly when an object is deleted (the deallocation is done automatically by garbage collection), you<br />

should not rely too much on this method.<br />

If you, in the constructor of SpamBasket, needed to call the constructor of one or more<br />

superclasses, you could call it like this: Basket.__init__(self). Note that in addition to<br />

supplying the ordinary parameters, you have to explicitly supply self because the superclass<br />

__init__ doesn’t know which instance it is dealing with.<br />

For more about the wonders of object-oriented programming in Python, see Chapter 7.<br />

Some Loose Ends<br />

Let me just quickly review a few other useful things before ending this appendix. Most useful<br />

functions and classes are put in modules, which are really text files with the file name extension<br />

.py that contain Python code. You can import these and use them in your own programs. For<br />

example, to use the function sqrt from the standard module math, you can do either<br />

import math<br />

x = math.sqrt(y)<br />

or<br />

from math import sqrt<br />

x = sqrt(y)<br />

For more information on the standard library modules, see Chapter 10.<br />

All the code in the module/script is run when it is imported. If you want your program to<br />

be both an importable module and a runnable program, you might want to add something like<br />

this at the end of it:<br />

if __name__ == "__main__": main()<br />

This is a magic way of saying that if this module is run as an executable script (that is, it is not<br />

being imported into another script), then the function main should be called. Of course, you<br />

could do anything after the colon there.<br />

And for those of you who want to make an executable script in UNIX, use the following first<br />

line to make it run by itself:<br />

#!/usr/bin/env python<br />

Finally, a brief mention of an important concept: exceptions. Some operations (such as<br />

dividing something by zero or reading from a nonexistent file) produce an error condition or<br />

exception. You can even make your own and raise them at the appropriate times.<br />

If nothing is done about the exception, your program ends and prints out an error message.<br />

You can avoid this with a try/except statement. For example:

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

Saved successfully!

Ooh no, something went wrong!