1. 程式人生 > >python中Fraction()方法的用法介紹

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