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.

17.9. Polymorphism 165Unfortunately,thisimplementationofadditionisnotcommutative. Iftheintegeristhefirstoperand,you get>>> print 1337 + startTypeError: unsupported operand type(s) for +: 'int' and 'instance'The problem is, instead of asking the Time object to add an integer, <strong>Python</strong> is asking an integer toaddaTimeobject,anditdoesn’tknowhowtodothat. Butthereisacleversolutionforthisproblem:the special method __radd__, which stands for “right-side add.” This method is invoked when aTime object appears on theright sideof the+operator. Here’s thedefinition:# inside class Time:def __radd__(self, other):return self.__add__(other)And here’s how it’sused:>>> print 1337 + start10:07:17Exercise 17.5 Writeanaddmethod for Points that works witheither a Point object or atuple:• If the second operand is a Point, the method should return a new Point whose x coordinate isthe sum of thexcoordinates of the operands, and likewise forthe ycoordinates.• If the second operand is a tuple, the method should add the first element of the tuple to the xcoordinate and thesecond element tothe ycoordinate, and returnanew Point withtheresult.17.9 PolymorphismType-baseddispatchisusefulwhenitisnecessary,but(fortunately)itisnotalwaysnecessary. Oftenyou can avoid it bywritingfunctions that workcorrectly for arguments withdifferent types.Manyofthefunctionswewroteforstringswillactuallyworkforanykindofsequence. Forexample,inSection 11.1we usedhistogramtocount thenumber oftimes each letterappears inaword.def histogram(s):d = dict()for c in s:if c not in d:d[c] = 1else:d[c] = d[c]+1return dThis function also works for lists, tuples, and even dictionaries, as long as the elements of s arehashable, sothey can be usedas keys ind.>>> t = ['spam', 'egg', 'spam', 'spam', 'bacon', 'spam']>>> histogram(t){'bacon': 1, 'egg': 1, 'spam': 4}

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

Saved successfully!

Ooh no, something went wrong!