Python type函数和isinstance函数区别 - Python零基础入门教程
目錄
- 一.Python type 函數(shù)簡介
- 二.Python isinstance 函數(shù)簡介
- 三.Python type 函數(shù)和 isinstance 函數(shù)區(qū)別
- 四.猜你喜歡
零基礎(chǔ) Python 學(xué)習(xí)路線推薦 : Python 學(xué)習(xí)目錄 >> Python 基礎(chǔ)入門
Python 變量,也稱 Python 數(shù)據(jù)類型。Python 變量一共六種類型:整數(shù)/浮點數(shù)/字符串/BOOL/列表/元組/字典;
一.Python type 函數(shù)簡介
**Python 內(nèi)置函數(shù) type,該函數(shù)主要用于解析判斷 Python 變量類型;**type 函數(shù)語法如下:
''' 函數(shù)描述:type 函數(shù)用于獲取變量類型; 參數(shù):object : 實例對象; 返回值:直接或者間接類名、基本類型; ''' type(object)二.Python isinstance 函數(shù)簡介
isinstance 函數(shù)是 **Python **中的一個內(nèi)置函數(shù),主要用于檢測變量類型,返回值是 bool 值 ,isinstance 函數(shù)語法如下:
''' 函數(shù)描述:主要用于檢測變量類型,返回值是 bool 值 參數(shù):object : 實例對象。classinfo : 可以是直接或者間接類名、基本類型或者由它們組成的元組。 返回值:如果對象的類型與classinfo類型相同則返回 True,否則返回 False。 '''isinstance(object,classinfo)三.Python type 函數(shù)和 isinstance 函數(shù)區(qū)別
- ** isinstance 函數(shù)會認(rèn)為子類是一種父類類型,考慮繼承關(guān)系。**
- ** type 函數(shù)不會認(rèn)為子類是一種父類類型,不考慮繼承關(guān)系。**
代碼分析
創(chuàng)建一個 Animation 對象,再創(chuàng)建一個繼承 Animation 對象的 Dog 對象,使用 isinstance 和 type 來比較 Animation 和 Animation 時,由于它們的類型都是一樣的,所以都返回了 True。
而 Dog 對象繼承于 Animation 對象,在使用 isinstance 函數(shù)來比較 Dog 和 Animation 時,由于考慮了繼承關(guān)系,所以返回了 True,使用 type 函數(shù)來比較 Dog 和 Animation 時,不會考慮 Dog 繼承自哪里,所以返回了 False。
** 總結(jié):如果要判斷兩個類型是否相同,則推薦使用 isinstance 函數(shù)**;
四.猜你喜歡
未經(jīng)允許不得轉(zhuǎn)載:猿說編程 ? Python type 函數(shù)和 isinstance 函數(shù)區(qū)別
總結(jié)
以上是生活随笔為你收集整理的Python type函数和isinstance函数区别 - Python零基础入门教程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scanner进阶详细讲解
- 下一篇: C语言 ##__VA_ARGS__ -