python中Fraction()方法的用法介绍

小编是想将字符串的分数,转换为浮点型的小数才接触到这个方法的。

源码如下:

class Fraction(numbers.Rational):
    """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() == 0.

    Fractions can also be constructed from:

      - numeric strings similar to those accepted by the
        float constructor (for example, '-2.3' or '1e10')

      - strings of the form '123/456'

      - float and Decimal instances

      - other Rational instances (including integers)

    """

这个类实现有理数。

在构造函数的双参数形式中,分数(8,6)将得到一个有理数,等于4/3。两种观点都必须是理性的。分子默认为0,分母默认为0

默认为1,所以Fraction(3)= 3,Fraction()= 0。

分数也可以由:

-数字字符串浮动构造函数(例如,'-2.3'或'1e10')

-“123/456”格式的字符串

-浮点和十进制实例

-其他Rational实例(包括整数)

具体实现将分数字符串转换为浮点型小数的实例代码如下:

import fractions

a = "3/4"

b = float(sum(fractions.Fraction(x) for x in a.split()))

print(type(b))
print(b)

打印结果为:

<class 'float'>
0.75
 

猜你喜欢

转载自blog.csdn.net/Odyssues_lee/article/details/83378379