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.

176 Chapter 18. InheritanceThey are also highly detailed; for some purposes, too detailed. A class diagram is a more abstractrepresentation of the structure of a program. Instead of showing individual objects, it shows classesand the relationships between them.There areseveral kinds of relationship between classes:• Objects in one class might contain references to objects in another class. For example, eachRectangle contains a reference to a Point, and each Deck contains references to many Cards.This kind of relationship iscalled HAS-A, as in, “aRectangle has aPoint.”• Oneclassmightinheritfromanother. ThisrelationshipiscalledIS-A,asin,“aHandisakindof aDeck.”• One class might depend on another in the sense that changes in one class would requirechanges intheother.A class diagram is a graphical representation of these relationships 2 . For example, this diagramshows the relationships betweenCard,DeckandHand.Deck*CardHandThe arrow with a hollow triangle head represents an IS-A relationship; in this case it indicates thatHand inherits from Deck.ThestandardarrowheadrepresentsaHAS-Arelationship;inthiscaseaDeckhasreferencestoCardobjects.The star (*) near the arrow head is a multiplicity; it indicates how many Cards a Deck has. Amultiplicity can be a simple number, like 52, a range, like 5..7 or a star, which indicates that aDeck can have any number ofCards.AmoredetaileddiagrammightshowthataDeckactuallycontainsalistofCards,butbuilt-intypeslikelistand dict areusually not included inclass diagrams.Exercise18.4 ReadTurtleWorld.py,World.pyandGui.pyanddrawaclassdiagramthatshowstherelationships among theclasses defined there.18.9 DebuggingInheritance can make debugging a challenge because when you invoke a method on an object, youmight not know which method willbe invoked.Suppose you are writing a function that works with Hand objects. You would like it to work withall kinds of Hands, like PokerHands, BridgeHands, etc. If you invoke a method like shuffle, you2 The diagrams I am using here are similar to UML (see wikipedia.org/wiki/Unified_Modeling_Language),with afew simplifications.

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

Saved successfully!

Ooh no, something went wrong!