在float(..)和{}之间有区别。在
float(..)将尝试解析string或任何具有__float__方法的对象。例如,int,float和{}有一个__float__方法。也可以为自定义类定义此类方法。在
如果要将复数转换为float(..),则会出错:>>> float(2+2j)
Traceback (most recent call last):
File "", line 1, in
TypeError: can't convert complex to float
float(..)函数的结果保证是float:如果__float__方法返回一个非浮点值,它将引发一个TypeError:
^{pr2}$
因此,一次简单的float(..)尝试就足够了:def is_number_like(x):
try:
float(x)
return True
except TypeError, ValueError:
return False
Python中的大多数numeric-like类型(比如numpy.int16)**支持这样的__float__方法。在
另一方面,int(..)与str和__int__方法一起工作。同样,如果您调用int(..),那么结果肯定是int。在
因此在python-3.x中,可以使用两个检查:一个用于float(..),另一个用于int(..):def is_number_like(x):
try:
int(x)
return True
except TypeError, ValueError:
try:
float(x)
return True
except TypeError, ValueError:
return False
或者,如果要返回类似数字的对象:def is_number_like(x):
try:
return int(x)
except TypeError:
try:
return float(x)
except TypeError:
return None
(如果两次尝试都失败,则返回None)。在
请注意,在python-2.x中,还有一个long类型(猜猜看,它与__long__一起工作)。在