它是早期python留下的,它基本上使一个元组成为相同的基础数字类型,例如
>>> type(10)
<type 'int'>
>>> type(10.0101010)
<type 'float'>
>>> nums = coerce(10, 10.001010)
>>> type(nums[0])
<type 'float'>
>>> type(nums[1])
<type 'float'>
它还允许对象在旧类中像数字一样工作 (这里用法的一个不好的例子是…)
>>> class bad:
... """ Dont do this, even if coerce was a good idea this simply
... makes itself int ignoring type of other ! """
... def __init__(self, s):
... self.s = s
... def __coerce__(self, other):
... return (other, int(self.s))
...
>>> coerce(10, bad("102"))
(102, 10)