Python isinstance函数介绍

yipeiwu_com6年前Python基础

isinstance(object, classinfo)

判断实例是否是这个类或者object

object是变量  
classinfo 是类型(tuple,dict,int,float) 
判断变量是否是这个类型  

复制代码 代码如下:
 
class objA:  
pass  
 
A = objA()  
B = 'a','v'  
C = 'a string'  
 
print isinstance(A, objA)  
print isinstance(B, tuple)  
print isinstance(C, basestring)  

输出结果:
复制代码 代码如下:

True  
True  
True  

  
不仅如此,还可以利用isinstance函数,来判断一个对象是否是一个已知的类型。 
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) 
True 
 
>>>isinstance(lst, (int, str, list) ) 
True 

另外:Python可以得到一个对象的类型 ,利用type函数:>>>lst = [1, 2, 3]>>>type(lst)<type 'list'> 

相关文章

使用Python画股票的K线图的方法步骤

使用Python画股票的K线图的方法步骤

导言 本文简单介绍了如何从网易财经获取某支股票的价格数据,并根据价格数据画出相应的日K线图。有助于新手了解并使用Python的相关功能。包括列表、自定义函数、for循环、if函数以及如何...

使用Python设置tmpfs来加速项目的教程

 对我当前工程进行全部测试需要花费不少时间。既然有 26 GB 空闲内存,为何不让其发挥余热呢? tmpfs 可以通过把文件系统保存在大内存中来加速测试的执行效率。 但...

详解python:time模块用法

详解python:time模块用法

time模块下有两种时间表示方法: 第1种是:时间戳的方式。是基于1970年1月1日0时0分0秒的偏移。浮点数。 第2种是:struct_time()类型的表示方法。gmtime()和l...

Python读取数据集并消除数据中的空行方法

如下所示: # -*- coding: utf-8 -*- # @ author hulei 2016-5-3 from numpy import * import operator...

python进程和线程用法知识点总结

python进程和线程用法知识点总结

今天我们使用的计算机早已进入多CPU或多核时代,而我们使用的操作系统都是支持“多任务”的操作系统,这使得我们可以同时运行多个程序,也可以将一个程序分解为若干个相对独立的子任务,让多个子任...