问题描述
Python内置的 coerce
函数的常见用法是什么?如果我不知道数值类型,我可以看到应用它。 html#coerce rel = noreferrer>根据文档,但是是否存在其他常见用法?我猜想在执行算术计算时也会调用 coerce()
,例如 eg 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?
推荐答案
它是,它基本上使一个数字元组成为相同的基础数字类型,例如
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()用来做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!