numbers — 数值抽象基类

源代码: Lib/numbers.py


The numbers 模块 ( PEP 3141 ) 定义层次结构为数值 抽象基类 which progressively define more operations. None of the types defined in this module are intended to be instantiated.

class numbers. Number

The root of the numeric hierarchy. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number) .

数值塔

class numbers. Complex

Subclasses of this type describe complex numbers and include the operations that work on the built-in complex type. These are: conversions to complex and bool , real , imag , + , - , * , / , ** , abs() , conjugate() , == ,和 != . All except - and != are abstract.

real

Abstract. Retrieves the real component of this number.

imag

Abstract. Retrieves the imaginary component of this number.

abstractmethod conjugate ( )

Abstract. Returns the complex conjugate. For example, (1+3j).conjugate() == (1-3j) .

class numbers. Real

Complex , Real adds the operations that work on real numbers.

In short, those are: a conversion to float , math.trunc() , round() , math.floor() , math.ceil() , divmod() , // , % , < , <= , > ,和 >= .

Real also provides defaults for complex() , real , imag ,和 conjugate() .

class numbers. Rational

子类型 Real and adds numerator and denominator properties. It also provides a default for float() .

The numerator and denominator values should be instances of Integral and should be in lowest terms with denominator positive.

numerator

抽象。

denominator

抽象。

class numbers. Integral

子类型 Rational and adds a conversion to int . Provides defaults for float() , numerator ,和 denominator . Adds abstract methods for pow() with modulus and bit-string operations: << , >> , & , ^ , | , ~ .

Notes for type implementers

Implementers should be careful to make equal numbers equal and hash them to the same values. This may be subtle if there are two different extensions of the real numbers. For example, fractions.Fraction 实现 hash() 如下:

def __hash__(self):
    if self.denominator == 1:
        # Get integers right.
        return hash(self.numerator)
    # Expensive check, but definitely correct.
    if self == float(self):
        return hash(float(self))
    else:
        # Use tuple's hash to avoid a high collision rate on
        # simple fractions.
        return hash((self.numerator, self.denominator))