python中type和isinstance的使用

2021-09-24 12:18:22 字數 736 閱讀 5331

a1 = [1, 2]

print(type(a1)) # class a: # 建立乙個空類

pass # 代表空行,讓編譯器不報錯

a = a() # 建立乙個物件

print(type(a)) # class b(a): # 建立乙個類b,繼承自類a

pass # 空行,沒有實際意義,僅僅讓編譯器不報錯

b = b() # 建立乙個類b的物件

print(type(b)) # # 用isinstance()函式判斷乙個物件是不是另乙個類的例項

print(isinstance(a, a)) # true 說明a是類a的乙個例項

print(isinstance(b, b)) # true 說明b是類b的乙個例項

print(isinstance(b, a)) # true 說明b是類a的乙個例項,因為b是b的乙個例項,而類b繼承自類a

Python中type和isinstance的區別

在python中,我們經常通過type和isinstance來判斷某個物件的型別,下面我們通過乙個簡單的例子來分析2個方法的區別 class animal object def init self,name self.name name class dog animal def init self,...

python 中type和object的關係

學習python的同學都知道這麼幾句話 那麼type和object是什麼關係呢?object是乙個新式類,我們可以通過object.class 和object.bases 來獲取object所屬的類核他的父類。object.class 這說明 object類是乙個type元類的例項。這與type是所...

python中的type 函式

type 是乙個內建函式,可以很方便地查詢物件資料型別 主要有兩種用法 乙個引數和三個引數 1 只使用乙個引數 print type 1 輸出 print typr str 輸出2 使用三個引數 classx object a 1x type x object,dict a 1 產生乙個新的型別 x...