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.

18.10. Glossary 177might get the one defined in Deck, but if any of the subclasses override this method, you’ll get thatversion instead.Anytimeyouareunsureabouttheflowofexecutionthroughyourprogram,thesimplestsolutionistoaddprintstatementsatthebeginningoftherelevantmethods. IfDeck.shuffleprintsamessagethat says something like Running Deck.shuffle, then as the program runs it traces the flow ofexecution.Asanalternative,youcouldusethisfunction,whichtakesanobjectandamethodname(asastring)and returns theclass that provides thedefinition of themethod:def find_defining_class(obj, meth_name):for ty in type(obj).mro():if meth_name in ty.__dict__:return tyHere’s an example:>>> hand = Hand()>>> print find_defining_class(hand, 'shuffle')So theshufflemethod for thisHand isthe one inDeck.find_defining_class uses the mro method to get the list of class objects (types) that will besearched formethods. “MRO” stands for“method resolution order.”Here’s a program design suggestion: whenever you override a method, the interface of the newmethod should be the same as the old. It should take the same parameters, return the same type,and obey the same preconditions and postconditions. If you obey this rule, you will find that anyfunctiondesignedtoworkwithaninstanceofasuperclass,likeaDeck,willalsoworkwithinstancesof subclasses likeaHand or PokerHand.Ifyou violate thisrule, your code will collapse like(sorry)ahouse of cards.18.10 Glossaryencode: To represent one set of values using another set of values by constructing a mapping betweenthem.class attribute: An attribute associated with a class object. Class attributes are defined inside aclass definition but outside any method.instance attribute: Anattributeassociated withaninstance of a class.veneer: A method or function that provides a different interface to another function without doingmuch computation.inheritance: The ability to define a new class that is a modified version of a previously definedclass.parent class: The classfrom which achild class inherits.child class: A new classcreated by inheritingfrom an existingclass; alsocalled a“subclass.”

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

Saved successfully!

Ooh no, something went wrong!