1. 基本語法
isinstance(object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct, indirect or virtual) subclass thereof. 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.
classinfo 處可以是 a class, type, or tuple of classes and types,
如果是 tuple,則滿足 tuple 中的任何一個即返回 True
2. 字串的型別判斷。
字串,分為 str 和 unicode,二者均繼承自 basestring
>>> isinstance(u'3.0', unicode) True >>> isinstance('3.0', str) True >>> isinstance(u'3.0', str) False >>> isinstance(u'3.0', str) False >>> isinstance(u'3.0', basestring) True >>> isinstance('3.0', basestring) True
3. 數字的型別判斷
數字分為 int 和 float,暫未發現二者共同的有效父類。
可以用 (int, float) tuple 來判斷是否為數字(int 或 float)
>>> isinstance('3', (int, float)) False >>> isinstance(3.0, (int, float)) True >>> isinstance(3, (int, float)) True >>> isinstance(3.0, float) True >>> isinstance(3.0, int) False >>> isinstance(3, float) False >>> isinstance(3, int) True