1 / 24

Topics in Python Object Oriented Programming 1

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

tate-olson
Télécharger la présentation

Topics in Python Object Oriented Programming 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Topics in PythonObject Oriented Programming 1 Professor Frank J. Rinaldo Creation Core - office 401

  2. 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()

  3. Sending and Receiving Messages • Define an Alien class Alien(object): “””An alien in a shooter game””” def die(self): print “The alien dies\n”

  4. 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”)

  5. 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

  6. 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)

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

  8. 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!

  9. 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

  10. 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

  11. 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!”

  12. 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

  13. Blackjack GameOverriding Base Class Methods class unprintable_Card(Card): “”” A card is ‘face down’ “”” def __str__(self): return “<unprintable>”

  14. 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

  15. 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)

  16. 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

  17. 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

  18. 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.”)

  19. 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.”

  20. 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

  21. 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)

  22. 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)

  23. 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.”)

  24. 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

More Related