What is Python#39;s coerce() used for?(Python 的 coerce() 是做什么用的?)
问题描述
Python 内置的 coerce 函数有哪些常见用途?如果我不知道数值 type
,我可以看到应用它"noreferrer">根据文档,但是否存在其他常见用法?我猜想在执行算术计算时也会调用 coerce()
,例如 x = 1.0 +2
.它是一个内置函数,所以大概它有一些潜在的常见用法?
What are common uses for Python's built-in coerce
function? I can see applying it if I do not know the type
of a numeric value as per the documentation, but do other common usages exist? I would guess that coerce()
is also called when performing arithmetic computations, e.g. x = 1.0 +2
. It's a built-in function, so presumably it has some potential common usage?
推荐答案
它是 早期的python,它基本上使一个数字元组成为相同的底层数字类型,例如
Its a left over from early python, it basically makes a tuple of numbers to be the same underlying number type e.g.
>>> type(10)
<type 'int'>
>>> type(10.0101010)
<type 'float'>
>>> nums = coerce(10, 10.001010)
>>> type(nums[0])
<type 'float'>
>>> type(nums[1])
<type 'float'>
这也是为了让对象在旧类中表现得像数字
(在这里使用它的一个不好的例子是......)
It is also to allow objects to act like numbers with old classes
(a bad example of its usage here would be ...)
>>> 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 的 coerce() 是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 的 coerce() 是做什么用的?


基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01