Python内置的coerce函数的常见用法是什么?如果我不知道数值as per the documentation的type,我可以考虑应用它,但是否存在其他常见用法?我猜在执行算术计算时也会调用coerce(),例如x = 1.0 +2。它是一个内置的函数,所以它可能有一些潜在的常见用途?
发布于 2013-01-24 15:48:30
它是从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)https://stackoverflow.com/questions/14486802
复制相似问题