Python type() 函數

Python 內置函數 Python 內置函數


描述

type() 函數如果你只有第一個參數則返回對象的類型,三個參數返回新的類型對象。

isinstance() 與 type() 區別:

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

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

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

語法

以下是 type() 方法的語法:

type(object)
type(name, bases, dict)

參數

  • name -- 類的名稱。
  • bases -- 基類的元組。
  • dict -- 字典,類內定義的命名空間變數。

返回值

一個參數返回對象類型, 三個參數,返回新的類型對象。


實例

以下展示了使用 type 函數的實例:

# 一個參數實例 >>> type(1) <type 'int'> >>> type('zaixian') <type 'str'> >>> type([2]) <type 'list'> >>> type({0:'zero'}) <type 'dict'> >>> x = 1 >>> type( x ) == int # 判斷類型是否相等 True # 三個參數 >>> class X(object): ... a = 1 ... >>> X = type('X', (object,), dict(a=1)) # 產生一個新的類型 X >>> X <class '__main__.X'>

type() 與 isinstance()區別:

class A: pass class B(A): pass isinstance(A(), A) # returns True type(A()) == A # returns True isinstance(B(), A) # returns True type(B()) == A # returns False

Python 內置函數 Python 內置函數