在項目中,我們會在每個接口驗證客戶端傳過來的參數類型,如果驗證不通過,返回給客戶端“參數錯誤”錯誤碼。
這樣做不但便于調試,而且增加健壯性。因為客戶端是可以作弊的,不要輕易相信客戶端傳過來的參數。
驗證類型用type函數,非常好用,比如
>>type('foo') == str
True
>>type(2.3) in (int,float)
True
既然有了type()來判斷類型,為什么還有isinstance()呢?
一個明顯的區別是在判斷子類。
type()不會認為子類是一種父類類型。
isinstance()會認為子類是一種父類類型。
千言不如一碼。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class Foo( object ): pass class Bar(Foo): pass print type (Foo()) = = Foo print type (Bar()) = = Foo print isinstance (Bar(),Foo) class Foo( object ): pass class Bar(Foo): pass print type (Foo()) = = Foo print type (Bar()) = = Foo print isinstance (Bar(),Foo) 輸出 True False True |
需要注意的是,舊式類跟新式類的type()結果是不一樣的。舊式類都是<type 'instance'>。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
class A: pass class B: pass class C( object ): pass print 'old style class' , type (A()) print 'old style class' , type (B()) print 'new style class' , type (C()) print type (A()) = = type (B()) class A: pass class B: pass class C( object ): pass print 'old style class' , type (A()) print 'old style class' , type (B()) print 'new style class' , type (C()) print type (A()) = = type (B()) 輸出 old style class < type 'instance' > old style class < type 'instance' > new style class < class '__main__.C' > True |
不存在說isinstance比type更好。只有哪個更適合需求。
總結
以上就是本文關于python數據類型判斷type與isinstance的區別實例解析的全部內容,希望對大家有所幫助。有什么問題可以留言,大家一起交流討論。
原文鏈接:http://www.pythontab.com/html/2013/pythonjichu_0827/549.html