objec ves
play

Objec(ves Defining our own classes Nov 15, 2017 Sprenkle - CSCI111 - PDF document

Objec(ves Defining our own classes Nov 15, 2017 Sprenkle - CSCI111 1 Review: Dic(onaries What is a dic(onary in Python? What is the syntax for crea(ng a new dic(onary? How do we access a keys value from a dic(onary? What


  1. Objec(ves • Defining our own classes Nov 15, 2017 Sprenkle - CSCI111 1 Review: Dic(onaries • What is a dic(onary in Python? • What is the syntax for crea(ng a new dic(onary? • How do we access a key’s value from a dic(onary? Ø What happens if there is no mapping for that key? • How do we create a key à value mapping in a dic(onary? • How can we iterate through a dic(onary? Nov 15, 2017 Sprenkle - CSCI111 2 1

  2. ABSTRACTIONS Nov 15, 2017 Sprenkle - CSCI111 3 Abstrac(ons • Provide ways to think about program and its data Ø Get the jist without the details • Examples we’ve seen encodeFile(filename, key) Ø Func(ons and methods • Used to perform some opera(on but we don’t need to know how they’re implemented Ø Dic(onaries • Know they map keys to values • Don’t need to know how the keys are organized/stored in the computer’s memory Ø Just about everything we do in this class… Nov 15, 2017 Sprenkle - CSCI111 4 2

  3. Classes and Objects • Provide an abstrac(on for how to organize and reason about data • Example: GraphWin class Ø Had a"ributes (i.e., data or state) background color, width, height, and (tle Ø Each GraphWin object had these a`ributes • Each GraphWin object had its own values for these a`ributes Ø Used methods (API) to modify the object’s state, get informa(on about a`ributes Nov 15, 2017 Sprenkle - CSCI111 5 Defining Our Own Classes • Oaen, we want to represent data or informa(on that we do not have a way to represent using built-in types or libraries • Classes provide way to organize and manipulate data Ø Organize: data structures used • E.g., ints, lists, dic(onaries, other objects, etc. Ø Manipulate: methods Nov 15, 2017 Sprenkle - CSCI111 6 3

  4. What is a Class? • Defines a new data type • Defines the class’s a"ributes (i.e., data or state) and methods Ø Methods are like func/ons within a class and are the class’s API Other objects Internal data Object o of manipulate using hidden from type methods Classname others Nov 15, 2017 Sprenkle - CSCI111 7 Defining a Card Class • Create a class that represents a playing card Ø How can we represent a playing card? Ø What informa(on do we need to represent a playing card? Nov 15, 2017 Sprenkle - CSCI111 8 4

  5. Represen(ng a Card object • Every card has two a`ributes: Ø Suite (one of “hearts”, “diamonds”, “clubs”, “spades”) Ø Rank • 2-10: numbered cards • 11: Jack • 12: Queen • 13: King • 14: Ace Nov 15, 2017 Sprenkle - CSCI111 9 Defining a New Class • Syntax: Typically starts with a capital letter Keyword class class ClassName: <method definitions> Nov 15, 2017 Sprenkle - CSCI111 10 5

  6. Card Class (Incomplete) Doc String class class Card: """ A class to represent a standard playing card. The ranks are ints: 2-10 for numbered cards, 11=Jack, 12=Queen, 13=King, 14=Ace. The suits are strings: 'clubs', 'spades', 'hearts', 'diamonds ’ .""" def def __init__(self, rank, suit): """Constructor for class Card takes int rank and string suit.""" self._rank = rank self._suit = suit Methods def def getRank(self): "Returns the card ’ s rank." return return self._rank def def getSuit(self): "Returns the card ’ s suit." return return self._suit card.py Nov 15, 2017 Sprenkle - CSCI111 11 Card Class (Incomplete) Doc String class class Card: """ A class to represent a standard playing card. The ranks are ints: 2-10 for numbered cards, 11=Jack, 12=Queen, 13=King, 14=Ace. The suits are strings: 'clubs', 'spades', 'hearts', 'diamonds ’ .""" def def __init__(self, rank, suit): """Constructor for class Card takes int rank and string suit.""" self._rank = rank Methods are like functions self._suit = suit Methods defined in a class def def getRank(self): "Returns the card ’ s rank." return return self._rank def def getSuit(self): "Returns the card ’ s suit." return return self._suit card.py Nov 15, 2017 Sprenkle - CSCI111 12 6

  7. Defining the Constructor • __ __init init__ __ method is like the constructor • In constructor, define instance variables Ø Data contained in every object Convention: Ø Also called a?ributes or fields named with _ • Constructor never returns anything First parameter of every method is self self - pointer to the object that method acts on def def __init__(self, rank, suit): """Constructor for class Card takes int rank and string suit.""" self._rank = rank Instance self._suit = suit variables Nov 15, 2017 Sprenkle - CSCI111 13 Review • How do we use the constructor for an object? Nov 15, 2017 Sprenkle - CSCI111 14 7

  8. Using the Constructor def __init__(self, rank, suit): def • As defined, constructor is called using Card(<rank>,<suit>) Card(<rank>,<suit>) Ø Do not pass anything for the self self parameter Ø Python handles for us • Passes the parameter Object card card automa3cally of type Card _rank = ? _suit = ? Nov 15, 2017 Sprenkle - CSCI111 15 Using the Constructor def def __init__(self, rank, suit): • As defined, constructor is called using Card(<rank>,<suit>) Card(<rank>,<suit>) Ø Do not pass anything for the self self parameter Ø Python handles, passing the parameter for us automa(cally Object card card • Example: of type Card Ø card card = Card(2, "hearts") = Card(2, "hearts") _rank = 2 Ø Creates a 2 of Hearts card _suit = "hearts" Ø Python passes card card as self self for us Nov 15, 2017 Sprenkle - CSCI111 16 8

  9. Review • How do we call a method on an object? Nov 15, 2017 Sprenkle - CSCI111 17 Accessor Methods • Need to be able to get informa(on about the object def def getRank(self): "Returns the card’s rank." • Have self self return self._rank return parameter • Return data/ def getSuit(self): def informa(on "Returns the card’s suit." return return self._suit card = Card(…, …) card = Card(…, …) • These methods will get called as card.getRank() card.getRank () and card.getSuit card.getSuit() () Ø Python plugs card card in for self self Nov 15, 2017 Sprenkle - CSCI111 18 9

  10. Another Special Method: __str__ • Returns a string def def __str__(self): """Returns a string that describes the describing the card as 'rank of object suit'.""" • Whenever you print print result = "" if if self._rank == 11: an object, Python result += "Jack" checks if the object’s elif elif self._rank == 12: __ __str str__ __ method is result += "Queen" defined elif elif self._rank == 13: result += "King" Ø Prints result of calling elif elif self._rank == 14: __str__ method result += "Ace" • str(<object>) else else: result += str(self._rank) also calls __ __str str__ __ result += " of " + self._suit method return return result Nov 15, 2017 Sprenkle - CSCI111 19 Using the Card Class def def main(): c1 = Card(14, "spades") Invokes the print(c1) __str__ method c2 = Card(2, "hearts") print(c2) Displays: Ace of spades Object c1 c1 of Object c2 c2 of 2 of hearts type Card type Card _rank = 14 _rank = 2 _suit = “ spades ” _suit = “ hearts ” Nov 15, 2017 Sprenkle - CSCI111 20 10

  11. Example: Rummy Value • Problem: Add a method to the Card class called getRummyValue getRummyValue that returns the value of the card in the game of Rummy • Procedure for defining a method (similar to func(ons) Ø What is the input? Ø What is the output? Ø What is the method signature/header? Ø What does the method do? • How do we call the method? card2.py Nov 15, 2017 Sprenkle - CSCI111 21 Card API • Based on what we’ve seen/done so far, what does the Card class’s API look like? Nov 15, 2017 Sprenkle - CSCI111 22 11

  12. Card API API Instance Object o of Variables: type Card _rank, _suit Implementa(on of methods is hidden • Card(<rank>, <suit>) • getRank() • getSuit() • getRummyValue() • __str__() Nov 15, 2017 Sprenkle - CSCI111 23 (not covered in class) Defining a Card Class • Create a class that represents a playing card Ø How can we represent a playing card? Ø What informa(on do we need to represent a playing card? • Do we need a class to represent a card? Ø Does any built-in data type naturally represent a card? Ø What are the tradeoffs to those approaches? Nov 15, 2017 Sprenkle - CSCI111 24 12

  13. Using the Card class • Having the Card class means that we can represent a Card in code Now that we have the Card class, how can we use it? Nov 15, 2017 Sprenkle - CSCI111 25 Using the Card class Now that we have the Card class, how can we use it? • Let’s write a simplified version of the game of War Ø Basically just part of a round • What are the rules of a round of War? war.py Nov 15, 2017 Sprenkle - CSCI111 26 13

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend