Python type() 函式



Python 的 **type() 函式** 是一個 內建函式,它返回指定物件的型別,通常用於除錯。**type()** 函式的兩個主要用例如下:

  • 當我們向該函式傳遞單個引數時,它將返回給定物件的型別。

  • 當傳遞三個引數時,它允許動態建立新的型別物件。

語法

以下是 Python **type()** 函式的語法:

type(object, bases, dict)
# or
type(object)

引數

Python **type()** 函式接受兩個引數:

  • **object** - 它表示一個物件,例如 列表字串 或任何其他可迭代物件。

  • **bases** - 這是一個可選引數,它指定一個基類。

  • **dict** - 這也是一個可選引數。它表示一個儲存名稱空間的字典。

返回值

Python **type()** 函式返回給定物件的型別。如果我們傳遞三個引數,它將返回一個新的型別物件。

type() 函式示例

練習以下示例以瞭解如何在 Python 中使用 **type()** 函式

示例:type() 函式的使用

以下示例顯示了 Python **type()** 函式的基本用法。在下面的程式碼中,我們顯示了最常用的 資料型別 的類。

var1 = 5
var2 = 5.2
var3 = 'hello'
var4 = [1,4,7]
var5 = {'Day1':'Sun','Day2':"Mon",'Day3':'Tue'}
var6 = ('Sky','Blue','Vast')
print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
print(type(var5))
print(type(var6))

以下是上述程式碼的輸出:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'tuple'>

示例:使用 type() 函式獲取類的型別

名為“type”的類是一個超類,所有其他類都派生自它。type 物件也是該類的例項。因此,將 type() 函式應用於 Python 類將返回“class type”作為結果。

print("Displaying the type of Python classes:")
print("Type of int class is", type(int))
print("Type of dict class is", type(dict))
print("Type of list class is", type(list))
print("Type of type class is", type(type))

上述程式碼的輸出如下:

Displaying the type of Python classes:
Type of int class is <class 'type'>
Type of dict class is <class 'type'>
Type of list class is <class 'type'>
Type of type class is <class 'type'>

示例:使用 type() 函式建立新的型別物件

如果我們向**type()**函式傳遞三個引數,它將建立一個新的型別物件。在下面的程式碼中,我們建立了“Tutorialspoint”作為主類,一個物件作為基類,以及一個包含兩個鍵值對的字典

Object = type("Tutorialspoint", (object, ), dict(loc="Hyderabad", rank=1))
print(type(Object))
print(Object)

以下是上述Python程式碼的輸出:

<class 'type'>
<class '__main__.Tutorialspoint'>
python_built_in_functions.htm
廣告