Session 13 CPSC 231 Tu02 Table of content
Session 13 CPSC 231 Tu#02
Table of content • Stanford Moss • Event-driven programming • Modules • Example 2
Stanford Moss • Moss (for a Measure Of Software Similarity) is an automatic system for determining the similarity of programs. • Please avoid plagiarism! 3
Event-driven programming • Most programs and devices like a cellphone respond to events. • You might move your mouse, and the computer responds. Or you click a button, and the program does something interesting. • All GUIs are basically event-drive. e. g: Turtle library • The program consists of two parts • The event object or the 'publisher' is responsible for maintaining a list of all the functions which should be called when an event happens. • It has a fire()method which loops over that list and calls all of the functions in turn. • The handlers or 'subscribers' are functions that you're going to call when the event actually happens. 4
Modules • Instead of creating one large file, you can divide your program to a number of smaller program files called modules • Benefits: 1 - Code reuse 2 - Modular programming • It allows us to independently compose and debug parts of big programs • E. g: Math, Random, etc. 5
Modules (cont’d) • A module contains functions that are available for use by other programs. • A client is a program that makes use of a function in a module. • A program can be both a module and a client • In order to use a module there are 5 necessary steps 6
Modules (cont’d) • 1 - In the client: Import the module • Import random • 2 - In the client: Qualify function calls • type the module name module followed by the dot operator (. ) and the function name • E. g: stdio. writeln(), math. sqrt(), etc. • 3 - In the module: Compose a test function • def main() 7
Modules (cont’d) def func 1(arg 1, arg 2, arg 3): {some_code} Our module. py def main(): a = float(sys. argv[1]) b = float(sys. argv[2]) c = float(sys. argv[3]) stdio. writeln(func 1(a, b, c)) 8
Modules (cont’d) • 4 - In the module: Eliminate global code • 5 - Make the module accessible to the client • The easiest solution is to have client and module in the same directory 9
Modules (cont’d) def func 1(arg 1, arg 2, arg 3): {some_code} def main(): a = float(sys. argv[1]) b = float(sys. argv[2]) c = float(sys. argv[3]) stdio. writeln(func 1(a, b, c)) If this. py file is being executed directly by the python command (and not via an import statement), then call main() if __name__ == '__main__': main() 10
Example • Compose a program of a bouncing ball that changes direction when upon hitting a wall 11
- Slides: 11