python - Python 的 coerce() 是做什么用的?

标签 python type-conversion python-2.x built-in

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

最佳答案

它是 early 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() 是做什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14486802/

相关文章:

javascript - 添加字符串和数字时,JavaScript 如何转换为字符串?

python - Python 2 如何比较字符串和整数?为什么列表比较大于数字,而元组大于列表?

python - 在 python 2 中用十六进制字符解码字符串

python - 由于缺少 TensorBoard 安装,Spyder Anaconda 从 Keras Libraries CNN : WARNING:root:Limited tf. compat.v2.summary API 中出现错误

python - 如何在循环中更新数组索引(IndexError : list index out of range)

python - 如何在 Django 中编辑内联表单集中的模型对象

ruby - 从 nil 到 hash 的隐式转换有 refine bug

java - 检查随机数的 boolean 方法

python - opencv 2.x中的内存泄漏

Python 创建数据并将其附加到新的 Excel 工作簿 pandas