Docstoc

Modules

Document Sample
Modules Powered By Docstoc
					Chapter 15. Modules

 Bernard Chen 2007
Modules
   Nodules are the highest level program
    organization unit, which packages
    program codes and data for reuse

   Actually, each “file” is a module
      (Look into Lib in Python24)
Why Use Modules?
    Modules provide an easy way to
     organize components into a system,
     by serving as packages of names

    Modules have at least three roles:
1.   Code Reuse
2.   Implementing shared services or data
3.   Make everything “lives” in a Module
Module Creation
   To define a module, use your text
    editor to type Python code into a text
    file
   You may create some functions or
    variables in that file
   You can call modules anything, but
    module filenames should end in .py
    suffix
Modules Usage
   Clients can use the module file we just
    wrote by running “import” statement

>>> import math
>>> import random
>>> import module1 # assume this is
             the file name we saved
Modules examples
   We create a file name module1:

def print_out(aa):
     print aa*3

x=1
y=2
Modules Example
   now we write another file named module2

import module1

module1.print_out(“Hello World!! ”)    # Use module1’s function
print module1.x, module1.y             # Reference module1’s variable

x=10
y=20

print x, y

   The result of execute this program is:
   Hello World!! Hello World!! Hello World!!
   12
   10 20
Modules Example
     You may import as many modules as you like, for
     example:

import module1
import module2

print module1.x
print module2.x

    The result of execute this program is:
1
10

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:3
posted:11/5/2011
language:English
pages:8