溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python中isinstance函數(shù)的介紹

發(fā)布時間:2020-05-22 16:37:45 來源:億速云 閱讀:235 作者:鴿子 欄目:編程語言

1. 簡介

isinstance() 函數(shù)是 python  中的一個內置函數(shù),主要用于檢測變量類型,返回值是bool值 ,在python內置函數(shù)中,與該函數(shù)相似的還有另外一個內置函數(shù)  type()。

 

2.語法


1

isinstance(object,classinfo)

參數(shù):

object : 實例對象。

classinfo : 可以是直接或者間接類名、基本類型或者由它們組成的元組。

返回值:如果對象的類型與classinfo類型相同則返回 True,否則返回 False。

 

1

2

3

4

a = 2

isinstance(a,int)      # 結果返回 True

isinstance(a,str)      # 結果返回 False

isinstance(a,(str,int,list))      # 是元組中的一個,結果返回 True

 

3.isinstance()與type()的區(qū)別

isinstance() 會認為子類是一種父類類型,考慮繼承關系。

type() 不會認為子類是一種父類類型,不考慮繼承關系。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

# !usr/bin/env python

# -*- coding:utf-8 _*-

"""

@Author:何以解憂

@Blog(個人博客地址): shuopython.com

@WeChat Official Account(微信公眾號):猿說python

@Github:www.github.com

 

@File:python_isinstance.py

@Time:2019/11/22 21:25

 

@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!

"""

 

 

class Animation:

    pass

 

class Dog(Animation):

    pass

 

print(isinstance(Animation(), Animation))    # returns True

print(type(Animation()) == Animation)        # returns True

print(isinstance(Dog(), Animation))          # returns True

print(type(Dog()) == Animation)              # returns False

輸出結果:

1

2

3

4

True

True

True

False


代碼分析:

創(chuàng)建一個Animation對象,再創(chuàng)建一個繼承Animation對象的Dog對象,使用 isinstance() 和 type() 來比較 Animation() 和 Animation時,由于它們的類型都是一樣的,所以都返回了 True。

而Dog對象繼承于Animation對象,在使用isinstance()函數(shù)來比較 Dog() 和 Animation時,由于考慮了繼承關系,所以返回了 True,使用 type() 函數(shù)來比較 Dog() 和 Animation時,不會考慮 Dog() 繼承自哪里,所以返回了 False。

如果要判斷兩個類型是否相同,則推薦使用isinstance()。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI