Sunday, May 19, 2013

Python Modules


What's a Module? 
A module is a Python file that (generally) has only defenitions of variables, functions, and classes. For example, a module might look like this:

Code Example 1 - moduletest.py
### EXAMPLE PYTHON MODULE
# Define some variables:
numberone = 1
ageofqueen = 78
 
# define some functions
def printhello():
    print "hello"
 
def timesfour(input):
    print input * 4
 
# define a class
class Piano:
    def __init__(self):
        self.type = raw_input("What type of piano? ")
        self.height = raw_input("What height (in feet)? ")
        self.price = raw_input("How much did it cost? ")
        self.age = raw_input("How old is it (in years)? ")
 
    def printdetails(self):
        print "This piano is a/an " + self.height + " foot",
        print self.type, "piano, " + self.age, "years old and costing\
 " + self.price + " dollars."
As you see, a module looks pretty much like your normal Python program.
So what do we do with a module? We import bits of it (or all of it) into other programs.
To import all the variables, functions and classes from moduletest.py into another program you are writing, we use the import operator. For example, to import moduletest.py into your main program, you would have this:
Code Example 2 - mainprogram.py
### mainprogam.py
### IMPORTS ANOTHER MODULE
import moduletest
This assumes that the module is in the same directory as mainprogram.py, or is a default module that comes with python. You leave out the '.py' at the end of the file - it is ignored. You normally put all import statements at the beginning of the python file, but technically they can be anywhere. In order to use the items in the module in your main program, you use the following:
Code Example 3 - mainprogram.py continued
### USING AN IMPORTED MODULE
# Use the form modulename.itemname
# Examples:
print moduletest.ageofqueen
cfcpiano = moduletest.Piano()
cfcpiano.printdetails()
As you see, the modules that you import act very much like the classes we looked at last lesson - anything inside them must be preceeded with modulename. for it to work.

No comments:

Post a Comment