12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

How to Structure a ProgramGenerally, a <strong>Python</strong> program consists of multiple text files containing <strong>Python</strong> statements.The program is structured as one main, top-level file, along with zero or moresupplemental files known as modules in <strong>Python</strong>.In <strong>Python</strong>, the top-level file contains the main flow of control of your program—thisis the file you run to launch your application. The module files are libraries of toolsused to collect components used by the top-level file (and possibly elsewhere). Toplevelfiles use tools defined in module files, and modules use tools defined in othermodules.Module files generally don’t do anything when run directly; rather, they define toolsintended for use in other files. In <strong>Python</strong>, a file imports a module to gain access to thetools it defines, which are known as its attributes (i.e., variable names attached toobjects such as functions). Ultimately, we import modules and access their attributesto use their tools.Imports and AttributesLet’s make this a bit more concrete. Figure 18-1 sketches the structure of a <strong>Python</strong>program composed of three files: a.py, b.py, and c.py. The file a.py is chosen to bethe top-level file; it will be a simple text file of statements, which is executed fromtop to bottom when launched. The files b.py and c.py are modules; they are simpletext files of statements as well, but they are not usually launched directly. Instead, asexplained previously, modules are normally imported by other files that wish to usethe tools they define.Top-levelModulesb.pya.pyStandardlibrarymodulesc.pyFigure 18-1. Program architecture in <strong>Python</strong>. A program is a system of modules. It has one toplevelscript file (launched to run the program), and multiple module files (imported libraries oftools). Scripts and modules are both text files containing <strong>Python</strong> statements, though the statementsin modules usually just create objects to be used later. <strong>Python</strong>’s standard library provides acollection of precoded modules.<strong>Python</strong> Program Architecture | 387

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

Saved successfully!

Ooh no, something went wrong!