Guide to Programming with Python Chapter Nine Working with/Creating Modules.

Slides:



Advertisements
Similar presentations
Topics in Python Blackjack & TKinter
Advertisements

Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
Guide to Programming with Python
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Geography 465 Modules and Functions Writing Custom Functions.
3D Game Programming All in One By Kenneth C. Finney.
Chapter 5 Black Jack. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 5-2 Chapter Objectives Provide a case study example from problem statement.
Chapter 10 Classes Continued
1 Outline 7.1 Introduction 7.2 Implementing a Time Abstract Data Type with a Class 7.3 Special Attributes 7.4Controlling Access to Attributes 7.4.1Get.
Fundamentals of Python: From First Programs Through Data Structures
Guide to Programming with Python
Chapter 10 Classes. Review of basic OOP concepts  Objects: comprised of associated DATA and ACTIONS (methods) which manipulate that data.  Instance:
An Object-Oriented Approach to Programming Logic and Design
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
BIT 1003 – Presentation 7. Contents GENERATIONS OF LANGUAGES COMPILERS AND INTERPRETERS VIRTUAL MACHINES OBJECT-ORIENTED PROGRAMMING SCRIPTING LANGUAGES.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Guide to Programming with Python Chapter Three Branching, while Loops, and Program Planning: The Guess My Number Game.
Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.
Modules. A module is a file containing Python definitions and statements intended for use in other Python programs. There are many modules as part of.
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 6 Value-Returning.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
More on Functions (Part 2) Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
11 Chapter 11 Object-Oriented Databases Database Systems: Design, Implementation, and Management 4th Edition Peter Rob & Carlos Coronel.
Guide to Programming with Python
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX
Writing Scripts Hadi Otrok COEN 346.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Final Review Dr. Bernard Chen University of Central Arkansas Spring 2012.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
November 28, 2005ICP: Chapter 9: Object Oriented Programming 1 Introduction to Computer Programming Chapter 9: Object Oriented Programming Michael Scherger.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
© 2006 Pearson Addison-Wesley. All rights reserved 2-1 Chapter 2 Principles of Programming & Software Engineering.
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 15. Modules Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Chapter 2 Principles of Programming and Software Engineering.
IST 210: PHP LOGIC IST 210: Organization of Data IST210 1.
Modules. Modules Modules are the highest level program organization unit, usually correspond to source files and serve as libraries of tools. Each file.
Exceptions and Handling
More on Functions (Part 2) Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Juancho Datu. What is a Module? File containing Python definitions and statements with the suffix ‘.py’ in the current directory For example file name:
Guide to Programming with Python
Python’s Modules Noah Black.
More on Functions (Part 2)
Python’s Modules by E. Esin GOKGOZ.
Control Statements Lecture 6 from Chapter 5.
IFS410: Advanced Analysis and Design
Truth tables: Ways to organize results of Boolean expressions.
Truth tables: Ways to organize results of Boolean expressions.
More About Objects and Methods
More on Functions (Part 2)
Namespaces – Local and Global
Guide to Programming with Python Book is by Michael Dawson
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
Python Modules.
Namespaces – Local and Global
Python Modules.
Presentation transcript:

Guide to Programming with Python Chapter Nine Working with/Creating Modules

2 Fm:

Creating Modules  Create, use, and even share your own modules  Reuse code –Could reuse the Card, Hand, and Deck classes for different card games  Manage large projects –Professional projects can be hundreds of thousands of lines long –Would be nearly impossible to maintain in one file 3

Using Modules  Module imported using filename, just like built-in modules  Import programmer-created module the same way you import a built-in module import random random.randrange(10) from random import * randrange(10) (import * operation may not work very well on Windows platforms, where the filesystem does not always have accurate information about the case of a filename!) 4 What else have you tried?

Writing Modules  Write module as a collection of related programming components, like functions and classes, in a single file  File is just Python file with extension.py ( games module is file games.py) class Player(object): """ A player for a game. """ def __init__(self, name, score = 0): self.name = name self.score = score def __str__(sefl): return "name=" + name + " score=" + str(score) def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = raw_input(question).lower() return response 5

if __name == " __main__ " class Player(object): """ A player for a game. """ def __init__(self, name, score = 0):... if __name__ == "__main__": test = Player("Tom", 100) print tet raw_input("\n\nPress the enter key to exit.")  Why do I need to do this? To make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file ( __name__ == "__main__" is true ) 6

Using Imported Functions and Classes num = games.ask_number(question = "How many?", low = 2, high = 5) player = games.Player(name, score)  Use imported programmer-created modules the same way as you use imported built-in modules 7

What’s are Defined in a Module?  The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings: import sys dir(sys)

Module Not Found?  The Module Search Path –When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH.  Modules are searched in the list of directories given by the variable sys.path import sys sys.path.append('/home/yye/lib/python')

Packages  Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py... effects/ Subpackage for sound effects __init__.py echo.py import sound.effects.echo #or from sound.effects import echo

The Blackjack Game - Pseudocode Deal each player and dealer initial two cards For each player While the player asks for a hit and the player is not busted Deal the player an additional card If there are no players still playing Show the dealer’s two cards Otherwise While the dealer must hit and the dealer is not busted Deal the dealer an additional card If the dealer is busted For each player who is still playing The player wins Otherwise For each player who is still playing If the player’s total is greater than the dealer’s total The player wins Otherwise, if the player’s total is less than the dealer’s total The player loses Otherwise The player pushes 11

The Blackjack Game – Class Hierarchy Figure 9.8: Blackjack classes Inheritance hierarchy of classes for the Blackjack game 12

The Blackjack Game - Classes Table 9.1: Blackjack classes Guide to Programming with Python 13

Summary  You can write, import, and even share your own modules  You write a module as a collection of related programming components, like functions and classes, in a single Python file  Programmer-created modules can be imported the same way that built-in modules are, with an import statement  You test to see if __name__ is equal to "__main__" to make a module identify itself as such 14

Key OOP Concepts  Inheritance –Inheriting vs. overriding (Implementing a new one or adding) –Polymorphism means that the same message can be sent to objects of different classes related by inheritance and achieve different and appropriate results. For example, when Human or Comput object calls flip_or_take() methods, they do things differently. Polymorphism enables objects of different types to be substituted (e.g., the human-vs-compute Flip game to human-vs-human Flip game).  Encapsulation –The inclusion within a program object of all the resources needed for the object to function: the methods and the data to hide the details of the inner workings from the client code. –Encapsulation is a principle of abstraction -- a concept or idea not associated with any specific instance (OOP attempts to abstract both data and code)