Constructs a Rational. Takes a string like '3/2' or '1.5', another Rational instance, a numerator/denominator pair, or a float. Examples -------- >>> Fraction(10, -8) Fraction(-5, 4) >>> Fraction(Fraction(1, 7), 5) Fractio
(cls, numerator=0, denominator=None, *, _normalize=True)
| 60 | |
| 61 | # We're immutable, so use __new__ not __init__ |
| 62 | def __new__(cls, numerator=0, denominator=None, *, _normalize=True): |
| 63 | """Constructs a Rational. |
| 64 | |
| 65 | Takes a string like '3/2' or '1.5', another Rational instance, a |
| 66 | numerator/denominator pair, or a float. |
| 67 | |
| 68 | Examples |
| 69 | -------- |
| 70 | |
| 71 | >>> Fraction(10, -8) |
| 72 | Fraction(-5, 4) |
| 73 | >>> Fraction(Fraction(1, 7), 5) |
| 74 | Fraction(1, 35) |
| 75 | >>> Fraction(Fraction(1, 7), Fraction(2, 3)) |
| 76 | Fraction(3, 14) |
| 77 | >>> Fraction('314') |
| 78 | Fraction(314, 1) |
| 79 | >>> Fraction('-35/4') |
| 80 | Fraction(-35, 4) |
| 81 | >>> Fraction('3.1415') # conversion from numeric string |
| 82 | Fraction(6283, 2000) |
| 83 | >>> Fraction('-47e-2') # string may include a decimal exponent |
| 84 | Fraction(-47, 100) |
| 85 | >>> Fraction(1.47) # direct construction from float (exact conversion) |
| 86 | Fraction(6620291452234629, 4503599627370496) |
| 87 | >>> Fraction(2.25) |
| 88 | Fraction(9, 4) |
| 89 | >>> Fraction(Decimal('1.47')) |
| 90 | Fraction(147, 100) |
| 91 | |
| 92 | """ |
| 93 | self = super(Fraction, cls).__new__(cls) |
| 94 | |
| 95 | if denominator is None: |
| 96 | if type(numerator) is int: |
| 97 | self._numerator = numerator |
| 98 | self._denominator = 1 |
| 99 | return self |
| 100 | |
| 101 | elif isinstance(numerator, numbers.Rational): |
| 102 | self._numerator = numerator.numerator |
| 103 | self._denominator = numerator.denominator |
| 104 | return self |
| 105 | |
| 106 | elif isinstance(numerator, (float, Decimal)): |
| 107 | # Exact conversion |
| 108 | self._numerator, self._denominator = numerator.as_integer_ratio() |
| 109 | return self |
| 110 | |
| 111 | elif isinstance(numerator, str): |
| 112 | # Handle construction from strings. |
| 113 | m = _RATIONAL_FORMAT.match(numerator) |
| 114 | if m is None: |
| 115 | raise ValueError('Invalid literal for Fraction: %r' % |
| 116 | numerator) |
| 117 | numerator = int(m.group('num') or '0') |
| 118 | denom = m.group('denom') |
| 119 | if denom: |
nothing calls this directly
no test coverage detected