Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f1bbf9c

Browse files
committed
Add coercions
1 parent b6957e4 commit f1bbf9c

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

Demo/classes/Rat.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,18 @@ def __coerce__(a, b):
5252
raise TypeError, 'Rat.__coerce__: bad other arg'
5353

5454
def __add__(a, b):
55+
if type(b) <> type(a):
56+
a, b = a.__coerce__(b)
57+
return a + b
5558
return rat(a.num*b.den + b.num*a.den, a.den*b.den)
5659

5760
def __sub__(a, b):
5861
return rat(a.num*b.den - b.num*a.den, a.den*b.den)
5962

6063
def __mul__(a, b):
64+
if type(b) <> type(a):
65+
a, b = a.__coerce__(b)
66+
return a * b
6167
return rat(a.num*b.num, a.den*b.den)
6268

6369
def __div__(a, b):
@@ -78,9 +84,13 @@ def test():
7884
l.sort()
7985
print l
8086
print rat(0, 1)
81-
print rat(1, 0)
8287
print a+1
8388
print a+1L
8489
print a+1.0
90+
try:
91+
print rat(1, 0)
92+
raise SystemError, 'should have been ZeroDivisionError'
93+
except ZeroDivisionError:
94+
print 'OK'
8595

86-
test()
96+
#test()

0 commit comments

Comments
 (0)