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() 不會認為子類是一種父類類型,不考慮繼承關系。
# !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:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累! """ class People: pass class body(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
輸出結果:
True
True
True
False
代碼分析:
創建一個People對象,再創建一個繼承People對象的body對象,使用 isinstance() 和 type() 來比較 People() 和 People時,由於它們的類型都是一樣的,所以都返回了 True。
而body對象繼承於People對象,在使用isinstance()函數來比較 body() 和 People時,由於考慮了繼承關系,所以返回了 True,使用 type() 函數來比較 body() 和 People時,不會考慮 body() 繼承自哪里,所以返回了 False。
如果要判斷兩個類型是否相同,則推薦使用isinstance()。
猜你喜歡:
轉載請注明:猿說Python » python type函數
技術交流、商務合作請直接聯系博主
掃碼或搜索:猿說python

猿說python
微信公眾號 掃一掃關注