-1

我有以下代码:

a_round = round (3.5)   # First use of a_round
a_round = 4.5   # Incompatible types, since a_round is regarded as an int

原来round()的返回值被认为是一个int。之所以如此,我得出结论是因为在第二个语句中,mypy 抱怨:

Incompatible types in assignment (expression has type "float",variable has type "int")

我使用的是 Python 3.5,所以它应该是一个浮点数。我错过了什么。我应该以某种方式向 mypy 暗示 Python 版本吗?具体如何?

4

3 回答 3

4

充分澄清:

type (round (3.5, 0)) # <class 'float'>
type (round (3.5)) # <class 'int'>
于 2016-09-05T14:19:04.533 回答
1

这取决于您的实现:

>>> round(3.5)
4
>>> type(round(3.5))
<class 'int'>
>>> round(3.5,1)
3.5
>>> type(round(3.5,1))
<class 'float'>

当然,在所有情况下创建一个浮点数都是微不足道的:

>>> float(round(3.5))
4.0
>>> type(float(round(3.5)))
<class 'float'>
于 2016-09-05T14:07:07.163 回答
0

让我们检查一下这个脚本:

a_round = round(3.5)   # First use of a_round
print(a_round.__class__)
a_round = 4.5   # Incompatible types, since a_round is regarded as an int
print(a_round.__class__)

在 python 2.7 上,结果是:

<type 'float'>
<type 'float'>

但是使用 python 3.5 将是:

<class 'int'>
<class 'float'>

解决方案:您应该在使用 python 3.5 时显式转换为浮动:

a_round = float(round(3.5))
于 2016-09-05T14:11:55.310 回答