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

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

内容简介: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的强制()用于?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Learning PHP 5

Learning PHP 5

David Sklar / O'Reilly / July, 2004 / $29.95

Learning PHP 5 is the ideal tutorial for graphic designers, bloggers, and other web crafters who want a thorough but non-intimidating way to understand the code that makes web sites dynamic. The book ......一起来看看 《Learning PHP 5》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具