type() 函數(shù)是 python 中的一個內(nèi)置函數(shù),主要用于獲取變量類型,在python內(nèi)置函數(shù)中,與該函數(shù)相似的還有另外一個內(nèi)置函數(shù) isinstance函數(shù)。
為房山等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及房山網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、房山網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
1 | type(object) |
參數(shù):
object : 實例對象。
返回值:直接或者間接類名、基本類型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | b=12.12 c="hello" d=[1,2,3,"rr"] e={"aa":1,"bb":"cc"}
print(type(b)) print(type(c)) print(type(d)) print(type(e))
print("***"*20)
classPerson(object): def__init__(self,name): self.name=name
defp(self): print("this is a methond")
print(Person) tom=Person("tom") print("tom實例的類型是:%s"%type(tom)) # 實例tom是Person類的對象。 |
輸出結(jié)果:
1 2 3 4 5 6 7 | <class'float'> <class'str'> <class'list'> <class'dict'> ************************************************************ <class'__main__.Person'> tom實例的類型是:<class'__main__.Person'> |
isinstance() 會認(rèn)為子類是一種父類類型,考慮繼承關(guān)系。
type() 不會認(rèn)為子類是一種父類類型,不考慮繼承關(guān)系。
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_type.py @Time:2019/11/22 21:25
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累! """
classPeople: pass
classbody(People): pass
print(isinstance(People(),People)) # returns True print(type(People())==People) # returns True print(isinstance(body(),People)) # returns True print(type(body())==People) # returns False |
輸出結(jié)果:
1 2 3 4 | True True True False |
代碼分析:
創(chuàng)建一個People對象,再創(chuàng)建一個繼承People對象的body對象,使用 isinstance() 和 type() 來比較 People() 和 People時,由于它們的類型都是一樣的,所以都返回了 True。
而body對象繼承于People對象,在使用isinstance()函數(shù)來比較 body() 和 People時,由于考慮了繼承關(guān)系,所以返回了 True,使用 type() 函數(shù)來比較 body() 和 People時,不會考慮 body() 繼承自哪里,所以返回了 False。
如果要判斷兩個類型是否相同,則推薦使用isinstance()。
網(wǎng)站欄目:python中type的含義和使用方法
分享鏈接:http://muchs.cn/article36/jpeisg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、網(wǎng)站排名、靜態(tài)網(wǎng)站、定制開發(fā)、網(wǎng)站改版、標(biāo)簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)