Guide to Programming with Python Book is by Michael Dawson

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Inheritance Inheritance Reserved word protected Reserved word super
Classes & Objects Computer Science I Last updated 9/30/10.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Object-oriented Programming Concepts
ASP.NET Programming with C# and SQL Server First Edition
Chapter 10 Classes Continued
Fundamentals of Python: From First Programs Through Data Structures
Guide to Programming with Python
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
I210 review (for final exam) Fall 2011, IUB. What’s in the Final Exam Multiple Choice (5) Short Answer (5) Program Completion (3) Note: A single-sided.
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
11 Chapter 11 Object-Oriented Databases Database Systems: Design, Implementation, and Management 4th Edition Peter Rob & Carlos Coronel.
Guide to Programming with Python
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.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
November 28, 2005ICP: Chapter 9: Object Oriented Programming 1 Introduction to Computer Programming Chapter 9: Object Oriented Programming Michael Scherger.
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Object Oriented Programming In Python
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.
Classes, Interfaces and Packages
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Introduction to Object-oriented Programming
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
OOP - Object Oriented Programming
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Object-Oriented Programming Concepts
Guide to Programming with Python
Programming Logic and Design Seventh Edition
Lecture 12 Inheritance.
COMPSCI 107 Computer Science Fundamentals
University of Central Florida COP 3330 Object Oriented Programming
MPCS – Advanced java Programming
CS-104 Final Exam Review Victor Norman.
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
Chapter 3 Inheritance © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Programming Language Concepts (CIS 635)
Lecture VI Objects The OOP Concept Defining Classes Methods
Creating and Deleting Instances Access to Attributes and Methods
Inheritance Basics Programming with Inheritance
Guide to Programming with Python
Week 6 Object-Oriented Programming (2): Polymorphism
Advanced Programming Behnam Hatami Fall 2017.
More Object-Oriented Programming
Computer Programming with JAVA
CISC/CMPE320 - Prof. McLeod
Fundaments of Game Design
Object-Oriented PHP (1)
Final and Abstract Classes
C++ Object Oriented 1.
Presentation transcript:

Guide to Programming with Python Book is by Michael Dawson https://www Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods

Objectives Create classes to define objects Write methods and create attributes for objects Instantiate objects from classes Restrict access to an object’s attributes Work with both new-style and old-style classes The Critter Caretaker Program Guide to Programming with Python

Python Is Object-Oriented Object-oriented programming (OOP): Methodology that defines problems in terms of objects that send messages to each other dir(1) In a game, a Missile object could send a Ship object a message to Explode OOP not required, unlike Java and C# Guide to Programming with Python

Understanding Object-Oriented Basics OOP allows representation of real-life objects as software objects (e.g., a dictionary as an object) Object: A single software unit that combines attributes and methods Attribute: A "characteristic" of an object; like a variable associated with a kind of object Method: A "behavior" of an object; like a function associated with a kind of object Class: Code that defines the attributes and methods of a kind of object (A class is a collection of variables and functions working with these variables)

Fundamental Concepts of OOP Information hiding Abstraction Encapsulation Modularity Polymorphism Inheritance Guide to Programming with Python

Creating Classes for Objects class Puppy(object): def __init__(self, name, color): self.name = name self.color = color def bark(self): print "I am", color, name puppy1 = Puppy("Max", "brown") puppy1.bark() puppy2 = Puppy("Ruby", "black") puppy2.bark() Class: Code that defines the attributes and methods of a kind of object Instantiate: To create an object; A single object is called an Instance

The Simple Critter Program class Critter(object): """A virtual pet""" def talk(self): print "Hi. I'm an instance of class Critter.” # main crit = Critter() crit.talk() Define class: Class name, begin with capital letter, by convention object: class based on (Python built-in type) Define a method Like defining a function Must have a special first parameter, self, which provides way for a method to refer to object itself

Class methods & “self” parameter Class methods have only one specific difference from ordinary functions--they must have an extra first name that has to be added to the beginning of the parameter list You do not give a value for this parameter(self) when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self. Guide to Programming with Python

Instantiating an Object crit = Critter() Create new object with class name followed by set of parentheses Critter() creates new object of class Critter Can assign a newly instantiated object to a variable of any name crit = Critter() assigns new Critter object to crit Avoid using variable that's same name as the class name in lowercase letters Guide to Programming with Python

Creating Multiple Objects crit1 = Critter() crit2 = Critter() Creating multiple objects is easy Two objects created here Each object is independent, full-fledged critter Guide to Programming with Python

Invoking a Method Any Critter object has method talk() crit.talk() Any Critter object has method talk() crit.talk() invokes talk() method of Critter object crit Prints string "Hi. I'm an instance of class Critter." simple_critter.py Guide to Programming with Python

Using Constructors Constructor: A special method that is automatically invoked right after a new object is created Usually write one in each class Usually sets up the initial attribute values of new object in constructor Guide to Programming with Python

Creating a Constructor def __init__(self): print "A new critter has been born!" New Critter object automatically announces itself to world __init__ Is special method name Automatically called by new Critter object Guide to Programming with Python

Initializing Attributes class Critter(object): def __init__(self, name): self.name = name ... crit1 = Critter("Poochie”) Can have object’s attributes automatically created and initialized through constructor (Big convenience!) self – first parameter in every instance method self receives reference to new Critter object name receives "Poochie" self.name = name creates the attribute name for object and sets to "Poochie" crit1 gets new Critter object

Accessing Attributes Assessing attributes using methods: talk() class Critter(object): ... def talk(self): print "Hi. I'm", self.name, "\n" crit1.talk() print crit1.name Assessing attributes using methods: talk() Uses a Critter object’s name attribute Receives reference to the object itself into self Accessing Attributes Directly Guide to Programming with Python

Printing an Object (How?) class Critter(object): ... def __str__(self): rep = "Critter object\n" rep += "name: " + self.name + "\n" return rep print crit1 __str__ is a special method that returns string representation of object (sample code) Guide to Programming with Python

Two More Special Methods class Puppy(object): def __init__(self): self.name = [] self.color = [] def __setitem__(self, name, color): self.name.append(name) self.color.append(color) def __getitem__(self, name): if name in self.name: return self.color[self.name.index(name)] else: return None dog = Puppy() dog['Max'] = 'brown' dog['Ruby'] = 'yellow’ print "Max is", dog['Max']

Using Class Attributes and Static Methods Class attribute: A single attribute that’s associated with a class itself (not an instance!) Static method: A method that’s associated with a class itself Class attribute could be used for counting the total number of objects instantiated, for example Static methods often work with class attributes Guide to Programming with Python

Creating a Class Attribute class Critter(object): total = 0 total = 0 creates class attribute total set to 0 Assignment statement in class but outside method creates class attribute Assignment statement executed only once, when Python first sees class definition Class attribute exists even before single object created Can use class attribute without any objects of class in existence Guide to Programming with Python

Accessing a Class Attribute class Critter(object): total = 0 def status(): print "Total critters", Critter.total status = staticmethod(status) def __init__(self, name): Critter.total += 1 print Critter.total #the class print crit1.total #the instance #crit1.total += 1 # won’t work; can't assign new value to a class attribute through instance

Creating a Static Method class Critter(object): ... def status(): print "Total critters", Critter.total status = staticmethod(status) status() Is static method Doesn't have self in parameter list because method will be invoked through class not object staticmethod() Built-in Python function Takes method and returns static method

Invoking a Static Method ... crit1 = Critter("critter 1") crit2 = Critter("critter 2") crit3 = Critter("critter 3") Critter.status() Invokes static method status() defined in Critter Prints a message stating that 3 critters exist Works because constructor increments class attribute total, which status() displays Guide to Programming with Python

Setting default values class Person(object): def __init__(self, name="Tom", age=20): self.name = name self.age = age def talk(self): print "Hi, I am", self.name def __str__(self): return "Hi, I am " + self.name one = Person(name="Yuzhen", age = "forever 20") print one two = Person() print two Guide to Programming with Python

Summary Object-oriented Programming (OOP) is a methodology of programming where new types of objects are defined An object is a single software unit that combines attributes and methods An attribute is a “characteristic” of an object; it’s a variable associated with an object (“instance variable”) A method is a “behavior” of an object; it’s a function associated with an object A class defines the attributes and methods of a kind of object Guide to Programming with Python

Summary (continued) Each instance method must have a special first parameter, called self by convention, which provides a way for a method to refer to object itself A constructor is a special method that is automatically invoked right after a new object is created A class attribute is a single attribute that’s associated with a class itself A static method is a method that’s associated with a class itself Guide to Programming with Python

Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game

More on OOP Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions”, and data rather than logic (from searchSOA.com) An object is a software bundle of related attributes and behavior (methods) A class is a blueprint or prototype from which objects are created Each object is capable of receiving messages, processing data, and sending messages to other objects (or client codes) and can be viewed as an independent module with a distinct role or functionality

Who Are You class Person(object): total = 0 #class attribute def __init__(self, name="Tom", age=20, location="Bloomington"): self.name = name self.age = age self.location = location Person.total += 1 def talk(self): print "Hi, I am", self.name, "and I am", self.age, "years old" def __str__(self): return "Hi, I am " + self.name + " and I am " + str(self.age) + " years old" print "Before creating instances: Person.total=", Person.total aperson = Person() print "Hi, I am", aperson.name, "and I am", aperson.age, "years old” aperson.talk() print aperson ruby = Person("Ruby", 21) print "Hi, I am", ruby.name, "and I am", ruby.age, "years old” ruby.talk() print ruby print "Now Person.total=", Person.total

Understanding Object Encapsulation Client code should Communicate with objects through method parameters and return values Avoid directly altering value of an object’s attribute Objects should Update their own attributes Keep themselves safe by providing indirect access to attributes through methods Guide to Programming with Python

Private vs Public Attributes and Methods Public: Can be directly accessed by client code Private: Cannot be directly accessed (easily) by client code Public attribute or method can be accessed by client code Private attribute or method cannot be (easily) accessed by client code By default, all attributes and methods are public But, can define an attribute or method as private Guide to Programming with Python

Creating Private Attributes class Critter(object): def __init__(self, name, mood): self.name = name # public attribute self.__mood = mood # private attribute name Created as any attribute before Public attribute (default) __mood Private attribute Two underscore characters make private attribute Begin any attribute with two underscores to make private Guide to Programming with Python

Accessing Private Attributes class Critter(object): ... def talk(self): print "\nI'm", self.name print "Right now I feel", self.__mood, "\n" Private attributes Can be accessed inside the class Can’t be accessed directly through object crit1.__mood won’t work Technically possible to access through object, but shouldn’t crit1._Critter__mood #instance._classname__variable Pseudo-encapsulation cannot really protect data from hostile code Guide to Programming with Python

Creating Private Methods class Critter(object): ... def __private_method(self): print "This is a private method." Like private attributes, private methods defined by two leading underscores in name __private_method() is a private method Guide to Programming with Python

Accessing Private Methods class Critter(object): ... def public_method(self): print "This is a public method." self.__private_method() Like private attributes, private methods Can be accessed inside class Can’t be accessed directly through object crit1.__private_method() won’t work Technically possible to access through object, but shouldn’t crit1._Critter__private_method()works Guide to Programming with Python

Controlling Attribute Access Instead of denying access to an attribute, can limit access to it Example: client code can read, but not change attribute Properties can manage how attribute is accessed or changed Guide to Programming with Python

Using Get Methods class Critter(object): ... def get_name(self): return self.__name crit = Critter("Poochie") print crit.get_name() Get method: A method that gets the value of an attribute, which is often private; by convention, name starts with “get” get_name() provides indirect access to __name Guide to Programming with Python

Using Set Methods class Critter(object): ... def set_name(self, new_name): if new_name == "": print "Critter's name can't be empty string." else: self.__name = new_name print "Name change successful. ” crit = Critter("Poochie") crit.set_name("Randolph") Set method: Sets an attribute, often private, to a value; by convention, name starts with "set”, e.g., set_name()

Using Properties (Optional) class Critter(object): ... name = property(get_name, set_name) Property: An interface that allows indirect access to an attribute by wrapping access methods around dot notation property() function Takes accessor methods and returns a property Supply with get and set methods for controlled access to private attribute Supply only get method for “read-only” property Guide to Programming with Python

Using Properties (Optional) >>> print crit.name Randolph >>> crit.name = "Sammy" Name change successful. Sammy >>> crit.name = "" Critter's name can't be empty string. Guide to Programming with Python

Respect Privacy Classes Objects Write methods (e.g., get & set methods) so no need to directly access object’s attributes Use privacy only for attributes and methods that are completely internal to operation of object Objects Minimize direct reading of object’s attributes Avoid directly altering object’s attributes Never directly access object’s private attributes or methods Guide to Programming with Python

New-Style and Old-Style Classes class Critter(object): # new-style class class Critter: # old-style class New-style class: A class that is directly or indirectly based on the built-in object Old-style class: A class that is not based on object, directly or indirectly New-style classes Introduced in Python 2.2 Significant improvements over old-style Create instead of old-style classes whenever possible Guide to Programming with Python

Summary Public attributes and methods can be directly accessed by client code Private attributes and methods cannot (easily) be directly accessed by client code A get method gets the value of an attribute; by convention, its name starts with “get” A set method sets an attribute to a value; by convention, its name starts with “set” Guide to Programming with Python

Guide to Programming with Python Chapter Nine Inheritance Working with multiple objects

OOP So Far Object-oriented programming is a programming language model organized around "objects” An object is a software bundle of related attributes and behavior (methods) A class is a blueprint or prototype from which objects are created class Player(object): def __init__(self, name = "Enterprise", fuel = 0): self.name = name self.fuel = fuel def status(self): ... myship = Ship("Appolo") myship.status() Object encapsulation & respect privacy

Objectives Inheritance makes objects (classes) special Derive new classes from existing ones Extend the definition of existing classes Override method definitions of existing classes Create objects of different classes in the same program Allow objects to communicate with each other Create more complex objects by combining simpler ones The Blackjack Game Guide to Programming with Python

Inheritance Models “is a” Relationship Car Van Sports car Convertible Animals Reptile Mammals Fish Dog Cat Human Guide to Programming with Python

Using Inheritance to Create New Classes Inheritance: An element of OOP that allows a new class to be based on an existing one where the new automatically gets (or inherits) all of the methods and attributes of the existing class The children classes get all the capabilities (methods) and properties (attributes) the parent class has; the children classes are also called derived classes Get the code for free! (code-reuse) – inheritance allows a new class to re-use code which already existed in another class (the parent class) Guide to Programming with Python

Derived Classes are New Classes To create specializations of existing classes or objects by adding new attributes and methods! often called subtyping when applied to classes. In specialization, the new class or object has data or behavior aspects that are not part of the inherited class. Over-ridding (e.g., over-ridding of the + operator, so + has different meaning, addition of two numbers, concatenation of two strings, etc) – the same method that does something different Guide to Programming with Python

Inheritance Example: Animal Class class Animal(object): def __init__(self, name): # Constructor self.name = name def get_name(self): return self.name class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr. Bojangles'), Dog('Lassie')] for animal in animals: print animal.talk() + ' I am ' + animal.get_name() Base class: A class upon which another is based; it is inherited from by a derived class Derived class: A class that is based upon another class; it inherits from a base class

Altering the Behavior of Inherited Methods: Overriding Override: To redefine how inherited method of base class works in derived class Two choices when overriding Completely new functionality vs. overridden method Incorporate functionality of overridden method, add more Guide to Programming with Python

Overriding to Create a New Version class Animal(object): def __init__(self, name): self.name = name def talk(self): return 'Hello!' class Cat(Animal): return 'Meow!'

Animal A > Animal B? class Animal(object): def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name def __gt__(self, other): #override comparison operators return self.age > other.age print Animal('Missy', 4) > Animal('Lassie', 3) Guide to Programming with Python

Overriding to Add More One can incorporate inherited method’s functionality in overridden method Class Card(object): ... class Positionable_Card(Card): def __init__(self, rank, suit, face_up = True): super(Positionable_Card, self).__init__(rank, suit) #invoke parent’s method by calling super() self.is_face_up = face_up Superclass: Another name for a base class Card is the superclass of Positionable_Card

Invoking Base Class Methods Incorporate inherited method’s functionality by calling super() Positionable_Card constructor invokes Card constructor and creates new attribute super() lets you invoke the method of a superclass First argument is the class name, Positionable_Card Second is reference to object itself, self Last is superclass method to call with parameters sent, __init__(rank, suit) Guide to Programming with Python

Understanding Polymorphism Polymorphism: Aspect of object-oriented programming that allows you to send same message to objects of different classes, related by inheritance, and achieve different but appropriate results for each object When you invoke talk() method of Cat object, you get different result than when you invoke the same method of a Animal (or Dog) object Guide to Programming with Python

Summary: What can be Done Through Inheritance New class gets all methods and attributes of existing class New class can also define additional methods and attributes, to create more specialized version of existing class New class can override the old methods When overriding a method, the new definition can have completely different functionality than the original definition or the new definition can incorporate the functionality of the original The super() function allows you to invoke the method of a superclass

A Little More on Inheritance Need to avoid yo-yo problem (caused by the too complicated inheritance hierarchy) Python supports a limited form of multiple inheritance (applies depth-first, left-to-right rule) class DerivedClass(Base1, Base2, Base3): ... Python interprets this by applying the depth-first, left-to right rule: if an attribute is not found in DerivedClass, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on)

Working with Multiple Objects We can have multiple objects in a program Message: Communication between objects; one object sends another a message when it invokes a method of the other (We already know that we can exchange information among functions through parameters and return values) Guide to Programming with Python

The Alien Blaster Program Figure 9.3: Visual representation of objects exchanging a message hero, a Player object, sends invader, an Alien object, a message. Guide to Programming with Python

Communications between Objects (Alien and Player) class Player(object): def blast(self, enemy): #enemy refers to the Alien object print "The player blasts an enemy." enemy.die() #invokes the Alien object’s die()method class Alien(object): def die(self): print "Good-bye, cruel universe.” hero = Player() invader = Alien() hero.blast(invader) # here an object is passed to a function of another object Guide to Programming with Python

Combining Objects Real-world objects often made up of other objects Can mimic composition and collection in OOP Drag racer composed of body, tires, and engine Drag_Racer class with attribute engine that references Race_Engine object Zoo is collection of animals Zoo class that has an attribute animals which is a list of different Animal objects Guide to Programming with Python

Blackjack Game: the Card Class class Card(object): """ A playing card. """ RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] SUITS = ["c", "d", "h", "s"] #class attributes def __init__(self, rank, suit): self.rank = rank #object attributes self.suit = suit def __str__(self): reply = self.rank + self.suit return reply card1 = Card(”A", ”d") # A Card object with rank "A" and suit "d" is the ace of diamonds print card1

Blackjack Game: the Hand Class class Hand(object): """ A hand of playing cards. """ def __init__(self): self.cards = [] #attribute – a list of Card objects def __str__(self): #special function, returns string for entire hand if self.cards: reply = "" for card in self.cards: reply += str(card) + " " else: reply = "<empty>" return reply def add(self, card): #adds card to list of cards self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card)

Combining Objects my_hand = Hand() card1 = Card("A", "c") card1 = Card("2", "c") my_hand.add(card1) my_hand.add(card2) print my_hand # Ac 2c your_hand = Hand() my_hand.give(card1, your_hand) my_hand.give(card2, your_hand) print your_hand # Ac 2c Guide to Programming with Python

Summary In object-oriented programming, objects can send messages to each other by invoking each other’s methods Objects can be composed of other objects or have collections of objects Guide to Programming with Python

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

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

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!) 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

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 )

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

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 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 If the player’s total is greater than the dealer’s total Otherwise, if the player’s total is less than the dealer’s total The player loses The player pushes

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

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

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

Key OOP Concepts Inheritance Encapsulation 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)

All done! Guide to Programming with Python