Python isinstance函數(shù)介紹
isinstance(object, classinfo)
判斷實(shí)例是否是這個(gè)類或者object
object是變量
classinfo 是類型(tuple,dict,int,float)
判斷變量是否是這個(gè)類型
class objA:
pass
A = objA()
B = 'a','v'
C = 'a string'
print isinstance(A, objA)
print isinstance(B, tuple)
print isinstance(C, basestring)
輸出結(jié)果:
True
True
True
不僅如此,還可以利用isinstance函數(shù),來判斷一個(gè)對(duì)象是否是一個(gè)已知的類型。
isinstance說明如下:
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
其第一個(gè)參數(shù)為對(duì)象,第二個(gè)為類型名或類型名的一個(gè)列表。其返回值為布爾型。若對(duì)象的類型與參數(shù)二的類型相同則返回True。若參數(shù)二為一個(gè)元組,則若對(duì)象類型與元組中類型名之一相同即返回True。
>>>isinstance(lst, list)
True
>>>isinstance(lst, (int, str, list) )
True
另外:Python可以得到一個(gè)對(duì)象的類型 ,利用type函數(shù):>>>lst = [1, 2, 3]>>>type(lst)<type 'list'>
相關(guān)文章
如何使用pyinstaller打包時(shí)引入自己編寫的庫(kù)
這篇文章主要介紹了如何使用pyinstaller打包時(shí)引入自己編寫的庫(kù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
解決使用Pycharm導(dǎo)入conda?environment時(shí)找不到python.exe
今天在使用conda創(chuàng)建環(huán)境之后,使用pycham發(fā)現(xiàn)找到自己的python環(huán)境但是找不到環(huán)境對(duì)應(yīng)的python.exe,這篇文章主要給大家介紹了關(guān)于如何解決使用Pycharm導(dǎo)入conda?environment時(shí)找不到python.exe的相關(guān)資料,需要的朋友可以參考下2023-10-10
將python打包的exe做成windows服務(wù)運(yùn)行的流程步驟
將 Python 腳本打包的 exe 文件作為 Windows 服務(wù)運(yùn)行,可以通過以下步驟實(shí)現(xiàn),Windows 服務(wù)是一種在后臺(tái)運(yùn)行的程序,通常不需要用戶交互,本文給大家介紹了一個(gè)完整的指南,需要的朋友可以參考下2025-02-02
Python實(shí)現(xiàn)統(tǒng)計(jì)英文單詞個(gè)數(shù)及字符串分割代碼
這篇文章主要介紹了Python實(shí)現(xiàn)統(tǒng)計(jì)英文單詞個(gè)數(shù)及字符串分割方法,本文分別給出代碼實(shí)例,需要的朋友可以參考下2015-05-05
Python數(shù)據(jù)類型相互轉(zhuǎn)換
當(dāng)涉及數(shù)據(jù)類型轉(zhuǎn)換時(shí),Python提供了多種內(nèi)置函數(shù)來執(zhí)行不同類型之間的轉(zhuǎn)換,本文主要介紹了Python數(shù)據(jù)類型相互轉(zhuǎn)換,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09
簡(jiǎn)介Python設(shè)計(jì)模式中的代理模式與模板方法模式編程
這篇文章主要介紹了Python設(shè)計(jì)模式中的代理模式與模板方法模式編程,文中舉了兩個(gè)簡(jiǎn)單的代碼片段來說明,需要的朋友可以參考下2016-02-02

