众所周知,python的数据类型有:int,float,str,list,tuple,dict,set。
在编写过程中,有时候需要判断变量的数据类型。我刚开始没想到如何优雅的写判断语句(if type(a)==type("asdf"),这么写感觉太傻了。。。。。),没想到直接有判断的函数——isinstance(参数1,参数2)。该函数用来判断一个变量(参数1)是否是已知的变量类型(参数2) ,返回值: 如果参数一的数据类型与参数二相同则返回 True,否则返回 False。
def judgetype(variate):
type=None
if isinstance(variate,int):
type = "int"
elif isinstance(variate,str):
type = "str"
elif isinstance(variate,float):
type = "float"
elif isinstance(variate,list):
type = "list"
elif isinstance(variate,tuple):
type = "tuple"
elif isinstance(variate,dict):
type = "dict"
elif isinstance(variate,set):
type = "set"
return type
if __name__ == '__main__':
a = 142
typename = judgetype(a)
print(typename)