1.type():獲取變量的數據類型,一般用於基本數據類型
>>> type(123)==type(456)
True
>>> type(123)==int
True
>>> type('abc')==type('123')
True
>>> type('abc')==str
True
>>> type('abc')==type(123)
False
2.isinstance():對於class的繼承關係來說,使用type()就很不方便。我們要判斷class的類型,可以使用isinstance()函數
如果繼承關係是:
object -> Animal -> Dog -> Husky
創建對象:
>>> a = Animal()
>>> d = Dog()
>>> h = Husky()
使用isinstance判讀:
>>> isinstance(h, Dog)
True
>>> isinstance(h, Animal)
True
能用type()判斷的基本類型也可以用isinstance()判斷:
>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'a', bytes)
True
3.dir():獲得一個對象的所有屬性和方法,它返回一個包含字符串的list
如:
dir(11)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']