python type函數(22)


 

 

 

1. 簡介

    type() 函數是 python  中的一個內置函數,主要用於獲取變量類型,在python內置函數中,與該函數相似的還有另外一個內置函數 isinstance函數

 

2.語法

type(object)

 

    參數:

        object : 實例對象。

    返回值:直接或者間接類名、基本類型

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)
 
class Person(object):
    def __init__(self, name):
        self.name = name
 
    def p(self):
        print("this is a  methond")
 
 
print(Person)
tom = Person("tom")
print("tom實例的類型是:%s" % type(tom))  # 實例tom是Person類的對象。

 

 

輸出結果:

<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
************************************************************
<class '__main__.Person'>
tom實例的類型是:<class '__main__.Person'>

 

 

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

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

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

輸出結果:

True
True
True
False

 

 

    代碼分析:

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

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

 
 

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

 

猜你喜歡:

1.python深拷貝和淺拷貝

2.python is和==區別

3.python 自定義時間格式time

4.python遞歸函數

 

轉載請注明:猿說Python » python type函數

 

技術交流、商務合作請直接聯系博主
掃碼或搜索:猿說python
python教程公眾號
猿說python
微信公眾號 掃一掃關注


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM