Python isinstance

来源:互联网 发布:知乎机构号运营方案 编辑:程序博客网 时间:2024/04/16 17:58
 python函数isinstance 2013-12-23 09:18:31
原文链接http://blog.chinaunix.net/uid-15007890-id-4048060.html

  1. isinstance  
  2.   
  3. isinstance(object, classinfo)   
  4. 判断实例是否是这个类或者object是变量  
  5.   
  6. classinfo 是类型(tuple,dict,int,float)  
  7. 判断变量是否是这个类型   
  8.   
  9. class objA:   
  10. pass   
  11.   
  12. A = objA()   
  13. B = 'a','v'   
  14. C = 'a string'   
  15.   
  16. print isinstance(A, objA)   
  17. print isinstance(B, tuple)   
  18. print isinstance(C, basestring)   
  19. 输出结果:   
  20. True   
  21. True   
  22. True   
  23.   
  24.    
  25. 不仅如此,还可以利用isinstance函数,来判断一个对象是否是一个已知的类型。  
  26. isinstance说明如下:  
  27.     isinstance(object, class-or-type-or-tuple) -> bool  
  28.       
  29.     Return whether an object is an instance of a class or of a subclass thereof.  
  30.     With a type as second argument, return whether that is the object's type.  
  31.     The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for  
  32.     isinstance(x, A) or isinstance(x, B) or ... (etc.).  
  33.   
  34. 其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。  
  35.   
  36. >>>isinstance(lst, list)  
  37. True  
  38.   
  39. >>>isinstance(lst, (int, str, list) )  
  40. True  
[python] view plaincopy
  1. 另外:Python可以得到一个对象的类型 ,利用type函数:>>>lst = [123]>>>type(lst)<type < span="" style="word-wrap: break-word;">'list'>  
0 0