python 資料型別檢查

2021-10-12 10:20:55 字數 2739 閱讀 6662

資料型別檢查

在實際介面自動化測試過程中,我們會發現介面的很多入參引數都標記了【string、int、float、array等等 】,這就迫使我們對入參得作下檢查工作,不然執行完成後,出錯了,**少的還能快速找到問題,**多了的話定位問題都要找半天。

首先,第一種是這樣的 「def function_check(number: int):」,方法和函式的檢查是一致的,這種方式的檢查,是輸入不符合的引數時,它只會顯示波浪線,滑鼠放在波浪線上時,也會有一段提示資訊,告訴你型別不符合,如下圖顯示

上的「 0.5 」顯示的下面顯示了波浪線,滑鼠放在上面也提示了「 expected type 『int』, got 『float』 instead 」,當然也不止檢查整型,浮點、字串、字典、元組都可以的,多個入參都可以進行檢查

def

check_str

(number:

str)

:return number

defcheck_float

(number:

float):

return number

defcheck_set

(number:

set)

:return number

defcheck_dict

(number:

dict):

return number

defcheck_list

(number:

list):

return number

defcheck

(number:

str, first:

int, second:

tuple):

return number, first, second

但是這種只是檢查入參,執行**時是能執行成功的,不會報錯,也不會丟擲錯誤資訊的。

isinstance()內建函式也是可以對入參進行檢查

如果不是對應的型別時會返回 true 或 false, 如下**展示效果

number =

5print

(isinstance

(number,

int)

)

執行後的結果:

d:\python\python37\python.exe f:

/git/auomationtest/testpytest/ch3/check_type.py

true

process finished with exit code 0

當然,我們也可以延伸,在函式或者方法裡去作判斷使用,如下**展示效果:

def

check_int

(num):if

isinstance

(num,

dict):

return num

else

:return

'型別錯誤'

print

(check_int(

'5')

)

執行後的結果:

d:\python\python37\python.exe f:

/git/auomationtest/testpytest/ch3/check_type.py

型別錯誤

process finished with exit code 0

也可以對引數進行多個型別檢查,如下**展示效果:

def

check_int

(num):if

isinstance

(num,

(dict

,float

,str

,tuple

,int))

:return num

else

:return

'型別錯誤'

# 只要符合其中乙個都會被正常列印

print

(check_int(

'5')

)

isinstance()內建函式,個人感覺判斷資料型別還是挺方便的,當然你要是還有更好的,歡迎來擾…

型別檢查的話,其實type()內建函式也是不能忽略的,相對來說,作判斷檢查的話個人認為靈敏度欠缺,如下**展示效果:

num=

5print

(type

(num)

)number =5if

type

(number)

isint

:print

(number)

type()查詢單個型別時還以的,但是對乙個入參進行多種檢查的話,個人覺得還是欠缺些… 沒有 **isinstance()**靈敏

一直都在努力變好中,希望您也是,加油!

python 資料型別檢查

資料型別檢查 在實際介面自動化測試過程中,我們會發現介面的很多入參引數都標記了 string int float array等等 這就迫使我們對入參得作下檢查工作,不然執行完成後,出錯了,少的還能快速找到問題,多了的話定位問題都要找半天。首先,第一種是這樣的 def function check n...

js檢查資料型別的方法

console.log typeof string console.log typeof 1 number console.log typeof true boolean console.log typeof undefined undefined console.log typeof null o...

資料型別概述 嚴格檢查模式

number js不區分小數和整數 123 整數 123.9 浮點數 1.23e3 科學計數法 90 負數 nan not a number infinity 表示無限大字串 abc abc 布林值true false 邏輯運算 與 或 非!比較運算 賦值 等於 型別不一樣,結果不一樣,也會為tru...