什么是Python的强制()用于?

栏目: Python · 发布时间: 6年前

内容简介:Python内置强制功能的常见用途是什么?我可以看到应用它,如果我不知道类型的数值http://stackoverflow.com/questions/14486802/what-is-pythons-coerce-used-for

Python内置强制功能的常见用途是什么?我可以看到应用它,如果我不知道类型的数值 as per the documentation ,但做其他常见的用法存在?我猜猜,执行算术计算时也会调用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)

http://stackoverflow.com/questions/14486802/what-is-pythons-coerce-used-for


以上所述就是小编给大家介绍的《什么是Python的强制()用于?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Python

Programming Python

Mark Lutz / O'Reilly Media / 2006-8-30 / USD 59.99

Already the industry standard for Python users, "Programming Python" from O'Reilly just got even better. This third edition has been updated to reflect current best practices and the abundance of chan......一起来看看 《Programming Python》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具