• Tidak ada hasil yang ditemukan

A playing-card example

Dalam dokumen A Practical Introduction to Python Programming (Halaman 143-146)

below. Another use is if the child class just wants to add on to one of the parent’s methods. In the example below, the child’sprint_varmethod calls the parent’sprint_varmethod and adds an additional line.

class Parent:

def __init__(self, a):

self.a = a

def print_var(self):

print("The value of this class's variables are:") print(self.a)

class Child(Parent):

def __init__(self, a, b):

Parent.__init__(self, a) self.b = b

def print_var(self):

Parent.print_var(self) print(self.b)

Note You can also inherit from Python built-in types, like strings (str) and lists (list), as well as any classes defined in the various modules that come with Python.

Note Your code can inherit from more than one class at a time, though this can be a little tricky.

14.4 A playing-card example

In this section we will show how to design a program with classes. We will create a simple hi-lo card game where the user is given a card and they have to say if the next card will be higher or lower than it. This game could easily be done without classes, but we will create classes to represent a card and a deck of cards, and these classes can be reused in other card games.

We start with a class for a playing card. The data associated with a card consists of its value (2 through 14) and its suit. TheCardclass below has only one method,__str__. This is a special method that, among other things, tells theprintfunction how to print aCardobject.

class Card:

def __init__(self, value, suit):

self.value = value self.suit = suit

def __str__(self):

names = ['Jack', 'Queen', 'King', 'Ace'] if self.value <= 10:

134 CHAPTER 14. OBJECT-ORIENTED PROGRAMMING return '{} of {}'.format(self.value, self.suit)

else:

return '{} of {}'.format(names[self.value-11], self.suit)

Next we have a class to represent a group of cards. Its data consists of a list ofCardobjects. It has a number of methods: nextCardwhich removes the first card from the list and returns it;

hasCardwhich returnsTrueorFalsedepending on if there are any cards left in the list;size, which returns how many cards are in the list; andshuffle, which shuffles the list.

import random class Card_group:

def __init__(self, cards=[]):

self.cards = cards

def nextCard(self):

return self.cards.pop(0)

def hasCard(self):

return len(self.cards)>0

def size(self):

return len(self.cards)

def shuffle(self):

random.shuffle(self.cards)

We have one more classStandard_deck, which inherits fromCard_group. The idea here is that Card_group represents an arbitrary group of cards, and Standard_deckrepresents a specific group of cards, namely the standard deck of 52 cards used in most card games.

class Standard_deck(Card_group):

def __init__(self):

self.cards = []

for s in ['Hearts', 'Diamonds', 'Clubs', 'Spades']:

for v in range(2,15):

self.cards.append(Card(v, s))

Suppose we had just created a single class that represented a standard deck along with all the common operations like shuffling. If we wanted to create a new class for a Pinochle game or some other game that doesn’t use the standard deck, then we would have to copy and paste the standard deck code and modify lots of things. By doing things more generally, like we’ve done here, each time we want a new type of deck, we can build off of (inherit from) what is inCard_group. For instance, a Pinochle deck class would look like this:

class Pinochle_deck(Card_group):

def __init__(self):

self.cards = []

for s in ['Hearts', 'Diamonds', 'Clubs', 'Spades']*2:

14.4. A PLAYING-CARD EXAMPLE 135 for v in range(9,15):

self.cards.append(Card(v, s))

A Pinochle deck has only nines, tens, jacks, queens, kings, and aces. There are two copies of each card in each suit.

Here is the hi-low program that uses the classes we have developed here. One way to think of what we have done with the classes is that we have built up a miniature card programming language, where we can think about how a card game works and not have to worry about exactly how cards are shuffled or dealt or whatever, since that is wrapped up into the classes. For the hi-low game, we get a new deck of cards, shuffle it, and then deal out the cards one at a time. When we run out of cards, we get a new deck and shuffle it. A nice feature of this game is that it deals out all 52 cards of a deck, so a player can use their memory to help them play the game.

deck = Standard_deck() deck.shuffle()

new_card = deck.nextCard() print('\n', new_card)

choice = input("Higher (h) or lower (l): ") streak = 0

while (choice=='h' or choice=='l'):

if not deck.hasCard():

deck = Standard_deck() deck.shuffle()

old_card = new_card

new_card = deck.nextCard()

if (choice.lower()=='h' and new_card.value>old_card.value or\

choice.lower()=='l' and new_card.value<old_card.value):

streak = streak + 1

print("Right! That's", streak, "in a row!")

elif (choice.lower()=='h' and new_card.value<old_card.value or\

choice.lower()=='l' and new_card.value>old_card.value):

streak = 0 print('Wrong.') else:

print('Push.') print('\n', new_card)

choice = input("Higher (h) or lower (l): ")

King of Clubs

Higher (h) or lower (l): l Right! That

'

s 1 in a row!

2 of Spades

136 CHAPTER 14. OBJECT-ORIENTED PROGRAMMING

Higher (h) or lower (l): h

Right! That

'

s 2 in a row!

Dalam dokumen A Practical Introduction to Python Programming (Halaman 143-146)