目錄
- 一.Python type 函式簡介
- 二.Python isinstance 函式簡介
- 三.Python type 函式和 isinstance 函式區別
- 四.猜你喜歡
零基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
Python 變數,也稱 Python 資料型別,Python 變數一共六種型別:整數/浮點數/字串/BOOL/串列/元組/字典;
一.Python type 函式簡介
**Python 內置函式 type,該函式主要用于決議判斷 Python 變數型別;**type 函式語法如下:
'''
函式描述:type 函式用于獲取變數型別;
引數:
object : 實體物件;
回傳值:直接或者間接類名、基本型別;
'''
type(object)
二.Python isinstance 函式簡介
isinstance 函式是 **Python **中的一個內置函式,主要用于檢測變數型別,回傳值是 bool 值 ,isinstance 函式語法如下:
'''
函式描述:主要用于檢測變數型別,回傳值是 bool 值
引數:
object : 實體物件,
classinfo : 可以是直接或者間接類名、基本型別或者由它們組成的元組,
回傳值:如果物件的型別與classinfo型別相同則回傳 True,否則回傳 False,
'''
isinstance(object,classinfo)
三.Python type 函式和 isinstance 函式區別
-
** isinstance 函式會認為子類是一種父型別別,考慮繼承關系,**
-
** type 函式不會認為子類是一種父型別別,不考慮繼承關系,**
!usr/bin/env python
-_- coding:utf-8 __-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:python type 函式和 isinstance 函式區別.py
@Time:2021/3/21 11:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程式人生的精彩需要堅持不懈地積累!"""
class Animation:
passclass Dog(Animation):
passprint(isinstance(Animation(), Animation)) # returns True
print(type(Animation()) == Animation) # returns True
print(isinstance(Dog(), Animation)) # returns True
print(type(Dog()) == Animation) # returns False'''
輸出結果:True
True
True
False'''
代碼分析
創建一個 Animation 物件,再創建一個繼承 Animation 物件的 Dog 物件,使用 isinstance 和 type 來比較 Animation 和 Animation 時,由于它們的型別都是一樣的,所以都回傳了 True,
而 Dog 物件繼承于 Animation 物件,在使用 isinstance 函式來比較 Dog 和 Animation 時,由于考慮了繼承關系,所以回傳了 True,使用 type 函式來比較 Dog 和 Animation 時,不會考慮 Dog 繼承自哪里,所以回傳了 False,
** 總結:如果要判斷兩個型別是否相同,則推薦使用 isinstance 函式**;
四.猜你喜歡
- Python 簡介
- Python Pycharm Anacanda 區別
- Python2.x 和 Python3.x,如何選擇?
- Python 配置環境
- Python Hello World 入門
- Python 代碼注釋
- Python 中文編碼
- Anaconda 是什么?Anconda 下載安裝教程
- Pycharm 提示:this license **** has been cancelled
- Pycharm 設定開發模板/字體大小/背景顏色
未經允許不得轉載:猿說編程 ? Python type 函式和 isinstance 函式區別
本文由博客 - 猿說編程 猿說編程 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/287977.html
標籤:Python
上一篇:Java面試題(一):面向物件
