Roll back r60248. It's useful to encourage users not to change Rational

instances.
This commit is contained in:
Jeffrey Yasskin 2008-02-01 07:05:46 +00:00
parent ca2b69f765
commit dc2964b0d8
2 changed files with 22 additions and 3 deletions

View File

@ -43,7 +43,7 @@ class Rational(RationalAbc):
"""
__slots__ = ('numerator', 'denominator')
__slots__ = ('_numerator', '_denominator')
# We're immutable, so use __new__ not __init__
def __new__(cls, numerator=0, denominator=1):
@ -93,8 +93,8 @@ class Rational(RationalAbc):
raise ZeroDivisionError('Rational(%s, 0)' % numerator)
g = gcd(numerator, denominator)
self.numerator = int(numerator // g)
self.denominator = int(denominator // g)
self._numerator = int(numerator // g)
self._denominator = int(denominator // g)
return self
@classmethod
@ -168,6 +168,14 @@ class Rational(RationalAbc):
result = new
return result
@property
def numerator(a):
return a._numerator
@property
def denominator(a):
return a._denominator
def __repr__(self):
"""repr(self)"""
return ('Rational(%r,%r)' % (self.numerator, self.denominator))

View File

@ -119,6 +119,17 @@ class RationalTest(unittest.TestCase):
r.__init__(2, 15)
self.assertEquals((7, 3), _components(r))
self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
self.assertEquals((7, 3), _components(r))
# But if you _really_ need to:
r._numerator = 4
r._denominator = 2
self.assertEquals((4, 2), _components(r))
# Which breaks some important operations:
self.assertNotEquals(R(4, 2), r)
def testFromFloat(self):
self.assertRaisesMessage(
TypeError, "Rational.from_float() only takes floats, not 3 (int)",