# numbers --- 數值的抽象基底類別¶

The numbers module (PEP 3141) defines a hierarchy of numeric abstract base classes which progressively define more operations. None of the types defined in this module are intended to be instantiated.

class numbers.Number

## 數值的階層¶

class numbers.Complex

real

imag

abstractmethod conjugate()

class numbers.Real

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

class numbers.Rational

Real 的子型別，並增加了 numeratordenominator 這兩種特性。它也會提供 float() 的預設值。

numeratordenominator 的值必須是 Integral 的實例且 denominator 要是正數。

numerator

denominator

class numbers.Integral

Rational 的子型別，並增加了 int 的轉換操作。為 float()numeratordenominator 提供了預設值。為 pow() 方法增加了求餘 (modulus) 和位元字串運算 (bit-string operations) 的抽象方法：<<>>&^|~

## 給型別實作者的註記¶

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))

### 加入更多數值 ABC¶

class MyFoo(Complex): ...
MyFoo.register(Real)

### 實作算術操作¶

We want to implement the arithmetic operations so that mixed-mode operations either call an implementation whose author knew about the types of both arguments, or convert both to the nearest built in type and do the operation there. For subtypes of Integral, this means that __add__() and __radd__() should be defined as:

class MyIntegral(Integral):

if isinstance(other, MyIntegral):
else:
return NotImplemented

if isinstance(other, MyIntegral):
elif isinstance(other, Integral):
return int(other) + int(self)
elif isinstance(other, Real):
return float(other) + float(self)
elif isinstance(other, Complex):
return complex(other) + complex(self)
else:
return NotImplemented

Complex 的子類別有 5 種不同的混合型別操作。我將上面提到所有不涉及 MyIntegralOtherTypeIKnowAbout 的程式碼稱作「模板 (boilerplate)」。aComplex 之子型別 A 的實例 (a : A <: Complex)，同時 b : B <: Complex。我將要計算 a + b

1. If A defines an __add__() which accepts b, all is well.

2. If A falls back to the boilerplate code, and it were to return a value from __add__(), we'd miss the possibility that B defines a more intelligent __radd__(), so the boilerplate should return NotImplemented from __add__(). (Or A may not implement __add__() at all.)

3. Then B's __radd__() gets a chance. If it accepts a, all is well.

4. 如果沒有成功回退到模板，就沒有更多的方法可以去嘗試，因此這裡將使用預設的實作。

5. 如果 B <: A，Python 會在 A.__add__ 之前嘗試 B.__radd__。這是可行的，因為它是透過對 A 的理解而實作的，所以這可以在交給 Complex 之前處理好這些實例。

If A <: Complex and B <: Real without sharing any other knowledge, then the appropriate shared operation is the one involving the built in complex, and both __radd__() s land there, so a+b == b+a.

def _operator_fallbacks(monomorphic_operator, fallback_operator):
def forward(a, b):
if isinstance(b, (int, Fraction)):
return monomorphic_operator(a, b)
elif isinstance(b, float):
return fallback_operator(float(a), b)
elif isinstance(b, complex):
return fallback_operator(complex(a), b)
else:
return NotImplemented
forward.__name__ = '__' + fallback_operator.__name__ + '__'
forward.__doc__ = monomorphic_operator.__doc__

def reverse(b, a):
if isinstance(a, Rational):
# Includes ints.
return monomorphic_operator(a, b)
elif isinstance(a, Real):
return fallback_operator(float(a), float(b))
elif isinstance(a, Complex):
return fallback_operator(complex(a), complex(b))
else:
return NotImplemented
reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
reverse.__doc__ = monomorphic_operator.__doc__

return forward, reverse