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.

17 other.__num, \<br />

18 self.__string + other.__string)<br />

19 else:<br />

20 raise TypeError, \<br />

21 'Illegal argument type for built-in operation'<br />

22<br />

23 def __mul__(self, num): # define for o*n<br />

24 if isinstance(num, int):<br />

25 return self.__class__(self.__num * num<br />

26 self.__string * num)<br />

27 else:<br />

28 raise TypeError, \<br />

29 'Illegal argument type for built-in operation'<br />

30<br />

31 def __nonzero__(self): # False if both are<br />

32 return self.__num or len(self.__string)<br />

33<br />

34 def __norm_cval(self, cmpres):# normalize cmp()<br />

35 return cmp(cmpres, 0)<br />

36<br />

37 def __cmp__(self, other): # define for cmp()<br />

38 return self.__norm_cval(<br />

39 cmp(self.__num, other.__num)) + \<br />

40 self.__norm_cval(<br />

41 cmp(self.__string, other.__string))<br />

Given the above criteria, we present the code below for numStr.py, with some sample execution:<br />

>>> a = NumStr(3, 'foo')<br />

>>> b = NumStr(3, 'goo')<br />

>>> c = NumStr(2, 'foo')<br />

>>> d = NumStr()<br />

>>> e = NumStr(string='boo')<br />

>>> f = NumStr(1)<br />

>>> a<br />

[3 :: 'foo']<br />

>>> b<br />

[3 :: 'goo']<br />

>>> c<br />

[2 :: 'foo']<br />

>>> d<br />

[0 :: '']<br />

>>> e<br />

[0 :: 'boo']<br />

>>> f<br />

[1 :: '']<br />

>>> a < b<br />

True<br />

>>> b < c<br />

False<br />

>>> a == a<br />

True<br />

>>> b * 2<br />

[6 :: 'googoo']<br />

>>> a * 3

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

Saved successfully!

Ooh no, something went wrong!