260 likes | 508 Views
Topics in Python Object Oriented Programming 1. Professor Frank J. Rinaldo Creation Core - office 401. Object Oriented Programming Sending and Receiving Messages. Objects interact by sending messages to each other Example: Define a Player class Player(object):
E N D
Topics in PythonObject Oriented Programming 1 Professor Frank J. Rinaldo Creation Core - office 401
Object Oriented ProgrammingSending and Receiving Messages • Objects interact by sending messages to each other • Example: • Define a Player class Player(object): “””A player in a shooter game””” def blast(self, enemy): print “The player blasts an enemy.\n” enemy.die()
Sending and Receiving Messages • Define an Alien class Alien(object): “””An alien in a shooter game””” def die(self): print “The alien dies\n”
Sending and Receiving Messages • Main program print “Death of an alien\n” hero = Player() invader = Alien() hero.blasts(invader) Raw_input(“\n\nPress the enter key to exit”)
Blackjack GameCreating a 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”] def __init__(self, rank, suit): self.reank = rank self.suit = suit def __str__(self): rep = self.rank + self.suit return rep
Blackjack GameCreating a Hand class class Hand(object): “”” A hand of playing cards””” def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = “” for card in self.cards: rep += str(card) + “ “ else: rep = “<empty>” def clear(self): self.cards = [] def add(self.card): seld.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other)hand.add(card)
Object Oriented ProgrammingInheritance • Base a new class on an already existing class • The new class automatically gets (or “Inherits”) all of the methods and attributes of the existing class • For example: • You create a base class for a car • 4 wheels • Engine • Etc • Then you create a more specific class for a Toyota based on the car class!
Blackjack GameCreating a Deck class • Create a new class to represent a deck (52) of cards • We can base this new class on our ‘Hand’ class • Note: The ‘Hand’ class has no limits on how many cards can be in a hand!
Blackjack GameCreating an Inherited class • We will base the ‘Deck’ class on the ‘Hand’ class • The ‘Deck’ class will ‘inherit’ methods & attributes from the ‘Hand’ class • Methods that will be inherited: • __init__() # constructor • __str__() # print • clear() # clear the ‘Hand’ • add() # add a card to the ‘Hand’ • give() # move a card from one ‘Hand’ to another
Blackjack GameExtending a class • We then extended (add to) the Deck class • Added more methods! • The methods are: • populate – create a deck of 52 cards • shuffle – shuffle the deck of cards • deal - deal the cards into hands for the players
Blackjack GameHand Class Class Deck(Hand): “”” A deck of playing cards. “”” def populate(self): for suit in Card.SUITS: for rank in Card.RANKS: self.add(Card(rank, suit)) def shuffle(self): import ramdom random.shuffle(self.cards) def deal(self, hands, per_hand = 1) for rounds in range(per_hand): for hand in hands: if self.cards: top_card = self.cards[0] self.give(top_card, hand) else: print “Out of cards!”
Object Oriented ProgrammingOverriding a method • We already saw that we create a new class that inherits methods from a base class • BUT we might want one of the methods to act differently than the base class method • To do this we will ‘override’ the method in the base class with a method in the new class
Blackjack GameOverriding Base Class Methods class unprintable_Card(Card): “”” A card is ‘face down’ “”” def __str__(self): return “<unprintable>”
Blackjack GameOverriding Base Class Methods class Positional_Card(Card): “”” A card can be face up or face down””” def __init__(self, rank, suit, face_up = True): super(Positionable_Card, self).__init__(rank, suit) self.is_face_up = face=up def __str__(self): if self.is_face_up: rep = super(Positionable_Card, self).__str__() else: rep = “XX” return rep def flip(self): self.is_face_up = not self.is_face_up
Object Oriented ProgrammingPolymorphism • Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface • In other words, you can treat different types of things the same • A simple example: • You class would work with: • Integers • Float-point numbers (reals)
Object Oriented ProgrammingUsing modules • Modules are like libraries • You can import modules into your programs • Example: • import random • Modules allow you to: • Reuse your code • Break large programs up into smaller logical modules • Share your modules with others • Modules are just Classes & attributes that are added to your program
Simple GameWriting Modules # simple game module class player(object): “”” A player for a game “”” def __init__(self, name, score = 0): self.name = name self.score = score def __str__(self): rep = self.name + “:\t” + str(self.score) return rep
Simple GameWriting Modules # simple game continued 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 def ask_number(question, low, high): “”” Ask for a number within a range “”” response = None while response not in range(low, high): response = int(raw_input(question) return response if __name__ == “__main__”: print “You ran this module directly & did not import it!\n” raw_input(“\n\nPress the enter key to exit.”)
Simple GameImporting Modules # Simple Game import games, random print “Welcome to the world’s simplest game” again = None while again != “n”: players = [] num = games.ask_number(question = “How many players (2 – 5): “, low = 2, high = 5) for i in range(num): name = raw_input(“Players name: “) score = random.randrange(100)+1 player = games.Player(name, score) players.append(player) print “\nHere are the game results:” for player in players: print player again = games.ask_yes_no(“\nDo you want to play again?: “) raw_input(“\n\nPress the enter key to exit.”
BlackJack GameThe ‘cards’ module # Cards module class Card(object): “”” A playing card ””” RANKS = [“A”, “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”] SUITS = [“c”, “d”, “h”, “s”] def __init__(self, rank, suit, face_up = True): self.rank = rank self.suit = suit self.is_face_up = face_up def __str__(self): if self.is_face_up: rep = self.rank + self.suit else: rep = “XX” return rep def flip(self) self.is_face_up = not self.is_face_up
BlackJack GameThe ‘cards’ module Class Hand(object): “”” A hand of playing cards “ def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = “” for card in self.cards: rep += str(card) + “\t” else: rep = “<empty>” return rep def clear(self): self.cards = [] def add(self): self.cards.append(card) def give(self, card, other.hand): self.cards.remove(card) other_hand.add(card)
BlackJack GameThe ‘cards’ module class Deck(Hand): “”” A deck of playing cards “”” def populate(self): for suit in Card.SUITS: for rank in Card.RANKS: self.add(Card(rank,suit)) def shuffle(self): import random random.shuffle(self.cards)
BlackJack GameThe ‘cards’ module def deal(self, hands, per_hand = 1); for rounds in range(per_hand): for hand in hands: if self.cards: top_card = self.cards[0] self.give(top_card, hand) else: print “Out of Cards” if __name__ == “__main__”: print “This is a module with classes for playing cards” raw_input(“\n\nPress the enter key to exit.”)
Homework • Due week 10 • Write a Python Program: • See problem #2 on page 289 of textbook. • In other words, allow 2 – 5 players, deal each player 1 card face up, player with highest card wins! • Use the “Cards Module” on pages 277 - 279 • Include: • Simple Specification Document • Simple Pseudocode • Python code • Demonstrate program in class