检查Python中变量的类型是否为特定类型
我想在Python中检查一个变量的类型是否是特定的类型。例如,我想检查变量 x
是否是一个整数(int)。
>>x=10
>>type(x)
<type 'int'>
但是我该怎么比较它们的类型呢?我试过这样做,但好像不太管用。
if type(10)== "<type 'int'>":
print 'yes'
那我该怎么做呢?
3 个回答
你可以使用以下几种方式:
>>> isinstance('ss', str)
True
>>> type('ss')
<class 'str'>
>>> type('ss') == str
True
>>>
int - > 整数
float -> 浮点数
list -> 列表
tuple -> 元组
dict -> 字典
对于类来说,有点不同:
旧类型的类:
>>> # We want to check if cls is a class
>>> class A:
pass
>>> type(A)
<type 'classobj'>
>>> type(A) == type(cls) # This should tell us
新类型的类:
>>> # We want to check if cls is a class
>>> class B(object):
pass
>>> type(B)
<type 'type'>
>>> type(cls) == type(B) # This should tell us
>>> #OR
>>> type(cls) == type # This should tell us
你的例子可以这样写:
if type(10) is int: # "==" instead of "is" would also work.
print 'yes'
但要注意,这可能并不完全符合你的需求。例如,如果你写了 10L
或者一个比 sys.maxint
更大的数字,而不是简单的 10
,那么它不会打印“yes”,因为 long
(这种数字的类型)并不是 int
。
另一种方法是,正如Martijn已经建议的,使用 isinstance()
这个内置函数,写法如下:
if isinstance(type(10), int):
print 'yes'
isinstance(instance, Type)
不仅在 type(instance) is Type
为真时返回 True
,还会在实例的类型是从 Type
派生时也返回 True
。所以,因为 bool
是 int
的子类,这样也适用于 True
和 False
。
但一般来说,最好不要检查具体的类型,而是检查你需要的特性。也就是说,如果你的代码无法处理某种类型,当尝试对该类型执行不支持的操作时,它会自动抛出异常。
不过,如果你需要对整数和浮点数进行不同的处理,你可能想要检查 isinstance(var, numbers.Integral)
(需要 import numbers
),如果 var
是 int
、long
、bool
或任何从这个类派生的用户自定义类型,这个检查会返回 True
。可以查看Python文档了解 标准类型层次结构 和 [numbers
模块]
使用 isinstance()
函数 来检查一个变量是否属于某种特定类型:
isinstance(x, int)
isinstance()
可以接受一个类型,或者一组类型(用括号括起来)来进行检查:
isinstance(x, (float, complex, int))
比如,它可以用来检查多个不同的数字类型。