當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。