This class implements rational numbers. In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3. Both arguments must be Rational. The numerator defaults to 0 and the denominator defaults to 1 so that Fraction(3) == 3 and Frac
| 36 | |
| 37 | |
| 38 | class Fraction(numbers.Rational): |
| 39 | """This class implements rational numbers. |
| 40 | |
| 41 | In the two-argument form of the constructor, Fraction(8, 6) will |
| 42 | produce a rational number equivalent to 4/3. Both arguments must |
| 43 | be Rational. The numerator defaults to 0 and the denominator |
| 44 | defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. |
| 45 | |
| 46 | Fractions can also be constructed from: |
| 47 | |
| 48 | - numeric strings similar to those accepted by the |
| 49 | float constructor (for example, '-2.3' or '1e10') |
| 50 | |
| 51 | - strings of the form '123/456' |
| 52 | |
| 53 | - float and Decimal instances |
| 54 | |
| 55 | - other Rational instances (including integers) |
| 56 | |
| 57 | """ |
| 58 | |
| 59 | __slots__ = ('_numerator', '_denominator') |
| 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: |
no outgoing calls
no test coverage detected