15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

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.

Addition<br />

We define the addition operator functionality as adding the numbers together and concatenating the<br />

strings; the tricky part is that the strings must be concatenated in the correct order. For example, let<br />

NumStr1 = [n1 :: s1] and NumStr2 = [n2 :: s2]. Then NumStr1 + NumStr2 is performed as [n1 + n2 ::<br />

s1 + s2] where + represents addition for numbers and concatenation for strings.<br />

Multiplication<br />

Similarly, we define the multiplication operator functionality as multiplying the numbers together and<br />

repeating or concatenating the strings, i.e., NumStr1 * NumStr2 = [n1 * n :: s1 * n].<br />

False Value<br />

This entity has a false value when the number has a numeric value of zero and the string is empty, i.e.,<br />

when NumStr = [0 :: ''].<br />

Comparisons<br />

Comparing a pair of NumStr objects, i.e., [n1 :: s1] vs. [n2 :: s2], we find nine different combinations<br />

(i.e., n1 > n2 and s1 < s2, n1 == n2 and s1 > s2, etc.). We use the normal numeric and lexicographic<br />

compares for numbers and strings, respectively, i.e., the ordinary comparison of cmp(obj1, obj2) will<br />

return an integer less than zero if obj1 < obj2, greater than zero if obj1 > obj2, or equal to zero if the<br />

objects have the same value.<br />

The solution for our class is to add both of these values and return the result. The interesting thing is<br />

that cmp() does not always return -1, 0, or 1 for us. It is, as described above, an integer less than, equal<br />

to, or greater than zero.<br />

In order to correctly compare our objects, we need __cmp__() to return a value of 1 if (n1 > n2) and (s1<br />

> s2), -1 if (n1 < n2) and (s1 < s2), and 0 if both sets of numbers and strings are the same, or if the<br />

comparisons offset each other, i.e., (n1 < n2) and (s1 > s2), or vice versa.<br />

Example 13.6. Multi-Type Class Customization (numstr.py)<br />

1 #!/usr/bin/env python<br />

2<br />

3 class NumStr(object):<br />

4<br />

5 def __init__(self, num=0, string=''):<br />

6 self.__num = num<br />

7 self.__string = string<br />

8<br />

9 def __str__(self): # define for str()<br />

10 return '[%d :: %r]' % \<br />

11 self.__num, self.__string)<br />

12 __repr__ = __str__<br />

13<br />

14 def __add__(self, other): # define for s+o<br />

15 if isinstance(other, NumStr):<br />

16 return self.__class__(self.__num + \

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

Saved successfully!

Ooh no, something went wrong!