python type函數

1. 簡介

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

 

2.語法


1

type(object)

參數:

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)

 

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類的對象。

輸出結果:

1

2

3

4

5

6

7

<class 'float'>

<class 'str'>

<class 'list'>

<class 'dict'>

************************************************************

<class '__main__.Person'>

tom實例的類型是:<class '__main__.Person'>

 

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

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_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

輸出結果:

1

2

3

4

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函數

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章