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
complextype. These are: conversions tocomplexandbool,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,Realadds 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 ¶
-
子类型
Realand addsnumeratoranddenominatorproperties. It also provides a default forfloat().The
numeratoranddenominatorvalues should be instances ofIntegraland should be in lowest terms withdenominatorpositive.- numerator ¶
-
抽象。
- denominator ¶
-
抽象。
- class numbers. Integral ¶
-
子类型
Rationaland adds a conversion toint. Provides defaults forfloat(),numerator,和denominator. Adds abstract methods forpow()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))