python是动态语言,定义变量时不用指定变量类型,在代码执行过程中,会根据变量的值确定变量类型。python中常用的变量类型有int
float
long
bool
str
list
tuple
set
dict
等,变量类型的判断常借助于types
库及内置的type(object)
和isinstance(object,class-or-type-or-tuple)
方法,下面分别来看一下如何通过这些方法进行变量类型的判断。
1. 使用types库结合type(object):
python中有一个内置的库types
,该库中有一系列type
类型的常量,如types.IntType
为int
类型,types.StringType
为str
类型,使用该库结合内置的type(object)
函数进行比较可以判断变量类型:
import types myInt = 1 myFloat = 1.1 myLong = 11111111111 myBool = True myStr = "teststring" myList = [1, 2] myTuple = (1, 2) mySet = set([1, 2]) myDict = {"name":"Lucy", "sex": "female"} # 检测类型 type(myInt) is types.IntType type(myFloat) is types.FloatType type(myLong) is types.LongType type(myBool) is types.BooleanType type(myStr) is types.String type(myList) is types.ListType type(myTuple) is types.TupleType # types库中没有对应的set类型,set可通过之后的方法进行判断 type(myDict) is types.DictType
2. 使用type(object):
为了方便起见,也可以不借助于types
包,直接使用内置的type(object)
方法与已知数据类型进行比较来判断变量数据类型:
type(myInt) is type(1) type(myFloat) is type(.1) type(myLong) is type(1111111111111) type(myBool) is type(True) type(myStr) is type("a") type(myList) is type([1]) type(myTuple) is type((1,)) type(mySet) is type(set([1])) type(myDict) is type({1:2})
3. 使用isinstance(object, class-or-type-or-tuple):
内置的isinstance(object, class-or-type-or-tuple)
也可以用来判断变量类型,返回一个布尔值:
isinstance(myInt, int) isinstance(myFloat, float) isinstance(myLong, float) isinstance(myBool, bool) isinstance(myStr, str) isinstance(myList, list) isinstance(myTuple, tuple) isinstance(mySet, set) isinstance(myDict, dict) # 第二个参数使用tuple类型 isinstance(myDict, (list, tuple, set, dict))
转载于:https://blog.51cto.com/xitongjiagoushi/1682216