首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python的coerce()是用来做什么的?

Python的coerce()是用来做什么的?
EN

Stack Overflow用户
提问于 2013-01-24 02:31:25
回答 1查看 18.3K关注 0票数 24

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-24 15:48:30

它是从early python遗留下来的,它基本上使一个数字元组成为相同的底层数字类型,例如

代码语言:javascript
运行
复制
>>> type(10)
<type 'int'>
>>> type(10.0101010)
<type 'float'>
>>> nums = coerce(10, 10.001010)
>>> type(nums[0])
<type 'float'>
>>> type(nums[1])
<type 'float'>

它还允许对象像旧类中的数字一样工作

(这里用法的一个不好的例子是...)

代码语言:javascript
运行
复制
>>> 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)
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14486802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档