当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python isinstance()用法及代码示例


Python支持面向对象的编程,因此可以使用python创建类。有时,必须了解mid-program哪些对象属于哪个类。 isinstance()执行此函数,因此使我们的编程任务更加容易。

语法:isinstance(obj,class)

参数:
obj:是否需要作为类的一部分进行检查的对象。
class:类/类型/类或类型的元组,需要对照该对象进行检查。


返回:是,如果通过单个类,则对象属于给定的类/类型;如果通过类/类型的元组,则对象属于任何类/类型,否则返回False。如果提到的有效类类型以外的任何其他类型,则引发TypeError。

代码1:演示isinstance对于本机类型的工作。

# Python 3 code to demonstrate  
# working of isinstance() 
# with native types 
  
# initializing native types 
test_int = 5
test_str = "GeeksforGeeks"
test_list = [1, 2, 3] 
  
# testing with isinstance 
print ("Is test_int integer?:" + str(isinstance(test_int, int))) 
print ("Is test_int string?:" + str(isinstance(test_int, str))) 
print ("Is test_str string?:" + str(isinstance(test_str, str))) 
print ("Is test_list integer?:" + str(isinstance(test_list, int))) 
print ("Is test_list list?:" + str(isinstance(test_list, list))) 
  
# testing with tuple 
print ("Is test_int integer or list or string?:" 
        + str(isinstance(test_int, (list, str, int)))) 
          
print ("Is test_list string or tuple?:" 
        + str(isinstance(test_list, (str, tuple))))

输出:

Is test_int integer?:True
Is test_int string?:False
Is test_str string?:True
Is test_list integer?:False
Is test_list list?:True
Is test_int integer or list or string?:True
Is test_list string or tuple?:False

代码#2:演示isinstance()与对象的结合使用

# Python 3 code to demonstrate  
# working of isinstance() 
# with objects 
  
# declaring classes 
class gfg1:
    a = 10
  
# inherited class 
class gfg2(gfg1):
    strng = 'GeeksforGeeks'
      
      
# initializing objects 
obj1 = gfg1() 
obj2 = gfg2() 
  
# checking istances 
print ("Is obj1 instance of gfg1?:" + str(isinstance(obj1, gfg1))) 
print ("Is obj2 instance of gfg2?:" + str(isinstance(obj2, gfg2))) 
print ("Is obj1 instance of gfg2?:" + str(isinstance(obj1, gfg2))) 
  
  
# check inhertance case 
# return true 
print ("Is obj2 instance of gfg1?:" + str(isinstance(obj2, gfg1)))

输出:

Is obj1 instance of gfg1?:True
Is obj2 instance of gfg2?:True
Is obj1 instance of gfg2?:False
Is obj2 instance of gfg1?:True



相关用法


注:本文由纯净天空筛选整理自manjeet_04大神的英文原创作品 Python | isinstance() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。