眾所周知,python的數(shù)據(jù)類型有:int,float檩禾,str挂签,list,tuple盼产,dict饵婆,set。
在編寫過(guò)程中戏售,有時(shí)候需要判斷變量的數(shù)據(jù)類型侨核。我剛開(kāi)始沒(méi)想到如何優(yōu)雅的寫判斷語(yǔ)句(if type(a)==type("asdf"),這么寫感覺(jué)太傻了。灌灾。搓译。。锋喜。)些己,沒(méi)想到直接有判斷的函數(shù)——isinstance(參數(shù)1,參數(shù)2)。該函數(shù)用來(lái)判斷一個(gè)變量(參數(shù)1)是否是已知的變量類型(參數(shù)2) 嘿般,返回值: 如果參數(shù)一的數(shù)據(jù)類型與參數(shù)二相同則返回 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)