2014-01-26 67 views

回答

8
isinstance(x, (int, long)) 

isinstance测试的第一个参数是由所述第二参数指定的一种或多种类型的一个实例。我们指定(int, long)来处理Python自动切换到long的情况,以表示非常大的数字,但如果您确定要排除long s,则可以使用int。有关更多详细信息,请参阅docs

至于为什么1.0 == 1,这是因为1.01代表相同的数字。 Python并不要求两个对象具有相同的类型才能被视为相同。

+0

@ user2864740:哦,对。谢谢。 – user2357112

+2

或者如果你还想接受Python的整数接口的第三方实现,你可以做'isinstance(x,numbers.Integral)'。例如'gmpy'。附带的好处,它也适用于Python 3。 –

1

上蟒并不大,但我用这个来检查:

i = 123 
f = 123.0 

if type(i) == type(f) and i == f: 
    print("They're equal by value and type!")  
elif type(i) == type(f): 
    print("They're equal by type and not value.") 
elif i == f: 
    print("They're equal by value and not type.") 
else: 
    print("They aren't equal by value or type.") 

返回:

They're equal by value and not type. 
+0

@downvoter这个答案有什么问题?它编译并回答了这个问题。 – michaelsnowden

+0

不是由我投票,但这可能是因为在Python中检查绝对类型是不鼓励的。这太精确了。它不考虑Python 2中的两个整数类型或任何子类。 'isinstance()'通常是你想要的。 –

0

就检查它是否是一个整数。

>>> def int_check(valuechk, valuecmp): 
     if valuechk == valuecmp and type(valuechk) == int: 
       return True 
     else: 
       return False 

>>> int_check(1, 1) 
True 
>>> int_check(1.0, 1) 
False