12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

18.8. Classdiagrams 175So when you create a Hand, <strong>Python</strong> invokes this initmethod:>>> hand = Hand('new hand')>>> print hand.cards[]>>> print hand.labelnew handBut the other methods are inherited from Deck, so we can use pop_card and add_card to deal acard:>>> deck = Deck()>>> card = deck.pop_card()>>> hand.add_card(card)>>> print handKing of SpadesA natural next stepistoencapsulate thiscode inamethod calledmove_cards:#inside class Deck:def move_cards(self, hand, num):for i in range(num):hand.add_card(self.pop_card())move_cards takes two arguments, a Hand object and the number of cards to deal. It modifies bothselfandhand,and returnsNone.In some games, cards are moved from one hand to another, or from a hand back to the deck. Youcan use move_cards for any of these operations: self can be either a Deck or a Hand, and hand,despite thename, can alsobe aDeck.Exercise 18.3 Write a Deck method called deal_hands that takes two parameters, the number ofhands and the number of cards per hand, and that creates new Hand objects, deals the appropriatenumber of cards per hand, and returnsalistof Hand objects.Inheritance is a useful feature. Some programs that would be repetitive without inheritance can bewritten more elegantly with it. Inheritance can facilitate code reuse, since you can customize thebehavior of parent classes without having to modify them. In some cases, the inheritance structurereflects thenatural structureof theproblem, which makes theprogram easier tounderstand.Ontheotherhand, inheritancecanmakeprogramsdifficulttoread. Whenamethodisinvoked, itissometimes not clear where to find its definition. The relevant code may be scattered among severalmodules. Also, many of the things that can be done using inheritance can be done as well or betterwithout it.18.8 ClassdiagramsSofarwehaveseenstackdiagrams,whichshowthestateofaprogram,andobjectdiagrams,whichshow the attributes of an object and their values. These diagrams represent a snapshot in the executionofaprogram, sothey change as theprogram runs.

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

Saved successfully!

Ooh no, something went wrong!