Python的coerce()有什么用?
Python里面有个内置的coerce
函数,它有什么常见的用法呢?我能想到的就是当我不知道一个数字的type
(类型)的时候可以用它,根据文档的说法是这样。但还有其他常见的用法吗?我猜在进行算术运算的时候,比如说x = 1.0 + 2
,也会调用coerce()
。既然它是个内置函数,那应该还有一些常见的用法吧?
2 个回答
2
Python核心编程中提到:
函数coerce()的作用是让程序员不必依赖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))
15
这是早期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)