什么是Python的coerce()用于?

Jzl*_*325 20 python type-conversion python-2.x built-in

Python的内置coerce函数有哪些常见用途?如果根据文档我不知道type数值,我可以看到应用它,但是还存在其他常见用法吗?我猜这也是在执行算术计算时调用的,例如.它是一个内置函数,所以可能它有一些潜在的常见用法?coerce() x = 1.0 +2

Gre*_*yer 13

它是早期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'>
Run Code Online (Sandbox Code Playgroud)

它也允许对象与旧类一样使用数字
(这里使用的一个坏例子是......)

>>> 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)
Run Code Online (Sandbox Code Playgroud)