mirror of https://github.com/python/cpython
Roll back r60248. It's useful to encourage users not to change Rational
instances.
This commit is contained in:
parent
ca2b69f765
commit
dc2964b0d8
|
@ -43,7 +43,7 @@ class Rational(RationalAbc):
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__slots__ = ('numerator', 'denominator')
|
__slots__ = ('_numerator', '_denominator')
|
||||||
|
|
||||||
# We're immutable, so use __new__ not __init__
|
# We're immutable, so use __new__ not __init__
|
||||||
def __new__(cls, numerator=0, denominator=1):
|
def __new__(cls, numerator=0, denominator=1):
|
||||||
|
@ -93,8 +93,8 @@ class Rational(RationalAbc):
|
||||||
raise ZeroDivisionError('Rational(%s, 0)' % numerator)
|
raise ZeroDivisionError('Rational(%s, 0)' % numerator)
|
||||||
|
|
||||||
g = gcd(numerator, denominator)
|
g = gcd(numerator, denominator)
|
||||||
self.numerator = int(numerator // g)
|
self._numerator = int(numerator // g)
|
||||||
self.denominator = int(denominator // g)
|
self._denominator = int(denominator // g)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
@ -168,6 +168,14 @@ class Rational(RationalAbc):
|
||||||
result = new
|
result = new
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
@property
|
||||||
|
def numerator(a):
|
||||||
|
return a._numerator
|
||||||
|
|
||||||
|
@property
|
||||||
|
def denominator(a):
|
||||||
|
return a._denominator
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
"""repr(self)"""
|
"""repr(self)"""
|
||||||
return ('Rational(%r,%r)' % (self.numerator, self.denominator))
|
return ('Rational(%r,%r)' % (self.numerator, self.denominator))
|
||||||
|
|
|
@ -119,6 +119,17 @@ class RationalTest(unittest.TestCase):
|
||||||
r.__init__(2, 15)
|
r.__init__(2, 15)
|
||||||
self.assertEquals((7, 3), _components(r))
|
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):
|
def testFromFloat(self):
|
||||||
self.assertRaisesMessage(
|
self.assertRaisesMessage(
|
||||||
TypeError, "Rational.from_float() only takes floats, not 3 (int)",
|
TypeError, "Rational.from_float() only takes floats, not 3 (int)",
|
||||||
|
|
Loading…
Reference in New Issue