12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

174 Chapter 18. InheritanceIn this case we are defining a “thin” method that expresses a list operation in terms that are appropriatefordecks.Asanotherexample,wecanwriteaDeckmethodnamedshuffleusingthefunctionshufflefromtherandommodule:# inside class Deck:def shuffle(self):random.shuffle(self.cards)Don’t forget toimportrandom.Exercise 18.2 Write a Deck method namedsortthat uses the list methodsortto sort the cards inaDeck. sortuses the__cmp__method wedefined todetermine sortorder.18.7 InheritanceThe language feature most often associated with object-oriented programming is inheritance. Inheritanceistheabilitytodefine a new classthat isamodified version of anexisting class.Itiscalled“inheritance”becausethenewclassinheritsthemethodsoftheexistingclass. Extendingthismetaphor, the existing classiscalled the parent and thenew classiscalled the child.As an example, let’s say we want a class to represent a “hand,” that is, the set of cards held by oneplayer. A hand is similar to a deck: both are made up of a set of cards, and both require operationslikeadding and removing cards.A hand is also different from a deck; there are operations we want for hands that don’t make sensefor a deck. For example, in poker we might compare two hands to see which one wins. In bridge,wemight compute ascorefor ahand inorder tomake a bid.This relationship between classes—similar,but different—lends itselftoinheritance.Thedefinitionofachildclassislikeotherclassdefinitions,butthenameoftheparentclassappearsinparentheses:class Hand(Deck):"""represents a hand of playing cards"""ThisdefinitionindicatesthatHandinheritsfromDeck;thatmeanswecanusemethodslikepop_cardandadd_cardfor Hands as wellas Decks.Handalsoinherits__init__fromDeck,butitdoesn’treallydowhatwewant: insteadofpopulatingthehand with52 new cards, theinit method for Hands should initializecardswithan empty list.Ifweprovide an initmethod intheHandclass, itoverrides the one intheDeckclass:# inside class Hand:def __init__(self, label=''):self.cards = []self.label = label

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!