类型转换 - Python 的 coerce() 有什么用?



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

它是早期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)

Python 核心编程 说:

函数强制()提供了程序员不依赖Python解释器,而是自定义的两种数值类型转换。

例如

>>> coerce(1, 2)
(1, 2)
>>>
>>> coerce(1.3, 134L)
(1.3, 134.0)
>>>
>>> coerce(1, 134L)
(1L, 134L)
>>>
>>> coerce(1j, 134L)
(1j, (134+0j))
>>>
>>> coerce(1.23-41j, 134L)
((1.23-41j), (134+0j))

最新更新