120 likes | 256 Views
Chapter 15. Modules. Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012. 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 Python). Why Use Modules?.
E N D
Chapter 15. Modules Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012
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 Python)
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: • Code Reuse • Implementing shared services or data • 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 will create two modules: module1 and module2 module2 will import data and functions from module1
module1.py print “First line of module1” def print_out(aa): print aa*3 x=1 y=2
module2.py print “First line of 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
module2 output • The result of execute this program is: • Hello World!! Hello World!! Hello World!! • 1 2 • 10 20
module3.py • 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
Important Notice • Import Happen Only ONCE If you try to import a module for the second time, Python will NOT execute it
Class Practice • Create two modules, each module has two functions and two variables • Create a third program which calls all functions and prints all variables in module1 and module2 you created