我有以下代码:
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,所以它应该是一个浮点数。我错过了什么我应该以某种方式暗示关于Python版本的mypy吗?究竟是怎么回事?
答案 0 :(得分: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'>
答案 1 :(得分:1)
完全澄清:
type (round (3.5, 0)) # <class 'float'>
type (round (3.5)) # <class 'int'>
答案 2 :(得分: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时,应该显式转换为float:
a_round = float(round(3.5))