python中如何判斷一個變量的數據類型

python中如何判斷一個變量的數據類型?(原創) 收藏 
import types 
type(x) is types.IntType # 判斷是否int 類型 
type(x) is types.StringType #是否string類型 
.........python

--------------------------------------------------------函數

超級噁心的模式,不用記住types.StringTypeorm

import types 
type(x) == types(1) # 判斷是否int 類型 
type(x) == type('a') #是否string類型對象

------------------------------------------------------string

使用內嵌函數:it

isinstance ( object, classinfo )io

Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object and object is an object of that type. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Changed in version 2.2: Support for a tuple of type information was added. 
Python能夠獲得一個對象的類型 ,利用type函數:function

>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>form


不只如此,還能夠利用isinstance函數,來判斷一個對象是不是一個已知的類型。class

isinstance說明以下:

    isinstance(object, class-or-type-or-tuple) -> bool
    
    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for 
    isinstance(x, A) or isinstance(x, B) or ... (etc.).

其第一個參數爲對象,第二個爲類型名或類型名的一個列表。其返回值爲布爾型。若對象的類型與參數二的類型相同則返回True。若參數二爲一個元組,則若對象類型與元組中類型名之一相同即返回True。

>>>isinstance(lst, list)
Trueisinstance(lst, (int, str, list))
True

>>>isinstance(lst, (int, str, list)) True

相關文章
相關標籤/搜索