return 回合类型 ()
return type of round ()
我有如下一段代码:
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()的return值被当成了int。
事实如此,我得出结论,因为在第二个陈述中,mypy 抱怨:
Incompatible types in assignment (expression has type "float",variable has type "int")
我用的是Python3.5,应该是float。我错过了什么。我应该以某种方式暗示 mypy 关于 Python 版本吗?具体如何?
这取决于您的实施:
>>> 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'>
让我们检查一下这个脚本:
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))
要充分说明:
type (round (3.5, 0)) # <class 'float'>
type (round (3.5)) # <class 'int'>
我有如下一段代码:
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()的return值被当成了int。 事实如此,我得出结论,因为在第二个陈述中,mypy 抱怨:
Incompatible types in assignment (expression has type "float",variable has type "int")
我用的是Python3.5,应该是float。我错过了什么。我应该以某种方式暗示 mypy 关于 Python 版本吗?具体如何?
这取决于您的实施:
>>> 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'>
让我们检查一下这个脚本:
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))
要充分说明:
type (round (3.5, 0)) # <class 'float'>
type (round (3.5)) # <class 'int'>