diff options
author | Guido van Rossum <guido@python.org> | 1994-10-09 22:36:28 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 1994-10-09 22:36:28 (GMT) |
commit | 2e61103c0b74ec4dc1ccd2fa2d308eb18ca73454 (patch) | |
tree | 42aa0cda3387abe29210022a309b6c4a57be1ddb /Demo/classes/Rat.py | |
parent | 74233b34e183f7b79ad43874144408516083dacf (diff) | |
download | cpython-2e61103c0b74ec4dc1ccd2fa2d308eb18ca73454.zip cpython-2e61103c0b74ec4dc1ccd2fa2d308eb18ca73454.tar.gz cpython-2e61103c0b74ec4dc1ccd2fa2d308eb18ca73454.tar.bz2 |
adapted to new overloading scheme
Diffstat (limited to 'Demo/classes/Rat.py')
-rwxr-xr-x | Demo/classes/Rat.py | 48 |
1 files changed, 27 insertions, 21 deletions
diff --git a/Demo/classes/Rat.py b/Demo/classes/Rat.py index d10e4df..7553745 100755 --- a/Demo/classes/Rat.py +++ b/Demo/classes/Rat.py @@ -1,7 +1,10 @@ # Rational numbers +from types import * def rat(num, den): + if type(num) == FloatType or type(den) == FloatType: + return num/den return Rat(num, den) @@ -16,12 +19,21 @@ class Rat: def __init__(self, num, den): if den == 0: raise ZeroDivisionError, 'rat(x, 0)' - g = gcd(num, den) + if type(den) == FloatType or type(num) == FloatType: + g = float(den) + else: + g = gcd(num, den) self.num = num/g self.den = den/g def __repr__(self): - return 'rat' + `self.num, self.den` + return 'Rat(%s, %s)' % (self.num, self.den) + + def __str__(self): + if self.den == 1: + return str(self.num) + else: + return '%s/%s' % (self.num, self.den) def __cmp__(a, b): c = a-b @@ -42,29 +54,23 @@ class Rat: def __coerce__(a, b): t = type(b) - if t == type(0): - return a, rat(b, 1) - if t == type(0L): - return a, rat(b, 1L) - if t == type(0.0): - return a.__float__(), b - if t == type(a) and a.__class__ == b.__class__: + if t == IntType: + return a, Rat(b, 1) + if t == LongType: + return a, Rat(b, 1L) + if t == FloatType: + return a, Rat(b, 1.0) + if t == InstanceType and a.__class__ == b.__class__: return a, b raise TypeError, 'Rat.__coerce__: bad other arg' def __add__(a, b): - if type(b) <> type(a): - a, b = a.__coerce__(b) - return a + b return rat(a.num*b.den + b.num*a.den, a.den*b.den) def __sub__(a, b): return rat(a.num*b.den - b.num*a.den, a.den*b.den) def __mul__(a, b): - if type(b) <> type(a): - a, b = a.__coerce__(b) - return a * b return rat(a.num*b.num, a.den*b.den) def __div__(a, b): @@ -75,21 +81,21 @@ class Rat: def test(): - print rat(-1L, 1) - print rat(1, -1) - a = rat(1, 10) + print Rat(-1L, 1) + print Rat(1, -1) + a = Rat(1, 10) print int(a), long(a), float(a) - b = rat(2, 5) + b = Rat(2, 5) l = [a+b, a-b, a*b, a/b] print l l.sort() print l - print rat(0, 1) + print Rat(0, 1) print a+1 print a+1L print a+1.0 try: - print rat(1, 0) + print Rat(1, 0) raise SystemError, 'should have been ZeroDivisionError' except ZeroDivisionError: print 'OK' |