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 Fraction(
| 180 | |
| 181 | |
| 182 | class Fraction(numbers.Rational): |
| 183 | """This class implements rational numbers. |
| 184 | |
| 185 | In the two-argument form of the constructor, Fraction(8, 6) will |
| 186 | produce a rational number equivalent to 4/3. Both arguments must |
| 187 | be Rational. The numerator defaults to 0 and the denominator |
| 188 | defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. |
| 189 | |
| 190 | Fractions can also be constructed from: |
| 191 | |
| 192 | - numeric strings similar to those accepted by the |
| 193 | float constructor (for example, '-2.3' or '1e10') |
| 194 | |
| 195 | - strings of the form '123/456' |
| 196 | |
| 197 | - float and Decimal instances |
| 198 | |
| 199 | - other Rational instances (including integers) |
| 200 | |
| 201 | """ |
| 202 | |
| 203 | __slots__ = ('_numerator', '_denominator') |
| 204 | |
| 205 | # We're immutable, so use __new__ not __init__ |
| 206 | def __new__(cls, numerator=0, denominator=None): |
| 207 | """Constructs a Rational. |
| 208 | |
| 209 | Takes a string like '3/2' or '1.5', another Rational instance, a |
| 210 | numerator/denominator pair, or a float. |
| 211 | |
| 212 | Examples |
| 213 | -------- |
| 214 | |
| 215 | >>> Fraction(10, -8) |
| 216 | Fraction(-5, 4) |
| 217 | >>> Fraction(Fraction(1, 7), 5) |
| 218 | Fraction(1, 35) |
| 219 | >>> Fraction(Fraction(1, 7), Fraction(2, 3)) |
| 220 | Fraction(3, 14) |
| 221 | >>> Fraction('314') |
| 222 | Fraction(314, 1) |
| 223 | >>> Fraction('-35/4') |
| 224 | Fraction(-35, 4) |
| 225 | >>> Fraction('3.1415') # conversion from numeric string |
| 226 | Fraction(6283, 2000) |
| 227 | >>> Fraction('-47e-2') # string may include a decimal exponent |
| 228 | Fraction(-47, 100) |
| 229 | >>> Fraction(1.47) # direct construction from float (exact conversion) |
| 230 | Fraction(6620291452234629, 4503599627370496) |
| 231 | >>> Fraction(2.25) |
| 232 | Fraction(9, 4) |
| 233 | >>> Fraction(Decimal('1.47')) |
| 234 | Fraction(147, 100) |
| 235 | |
| 236 | """ |
| 237 | self = super(Fraction, cls).__new__(cls) |
| 238 | |
| 239 | if denominator is None: |
no outgoing calls
searching dependent graphs…