當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python type()用法及代碼示例

在本教程中,我們將借助示例了解 Python type() 函數。

type() 函數或者返回對象的類型,或者返回基於傳遞的參數的新類型對象。

示例

prime_numbers = [2, 3, 5, 7]

# check type of prime_numbers
result = type(prime_numbers)
print(result)

# Output: <class 'list'>

type() 語法

type() 函數有兩種不同的形式:

# type with single parameter
type(object)

# type with 3 parameters
type(name, bases, dict)

參數:

type() 函數采用單個 object 參數。

或者,它需要 3 個參數

  • name- 類名;成為 __name__ 屬性
  • bases- 列出基類的元組;成為__bases__屬性
  • dict- 一個字典,它是包含類主體定義的命名空間;成為__dict__屬性

返回:

type() 函數返回

  • 對象的類型,如果隻傳遞一個對象參數
  • 如果傳遞了 3 個參數,則為新類型

示例 1:type() 帶有 Object 參數

numbers_list = [1, 2]
print(type(numbers_list))

numbers_dict = {1: 'one', 2: 'two'}
print(type(numbers_dict))

class Foo:
    a = 0

foo = Foo()
print(type(foo))

輸出

<class 'list'>
<class 'dict'>
<class '__main__.Foo'>

如果需要檢查對象的類型,最好使用Python isinstance() function。這是因為 isinstance() 函數還會檢查給定對象是否是子類的實例。

示例 2:type() 有 3 個參數

o1 = type('X', (object,), dict(a='Foo', b=12))
print(type(o1))

print(vars(o1))

class test:
  a = 'Foo'
  b = 12
  
o2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(o2))
print(vars(o2))

輸出

<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__doc__': None}

在程序中,我們使用了返回__dict__ 屬性的Python vars() function__dict__ 用於存儲對象的可寫屬性。

如有必要,您可以輕鬆更改這些屬性。例如,如果您需要將 o1__name__ 屬性更改為 'Z' ,請使用:

o1.__name = 'Z'

相關用法


注:本文由純淨天空篩選整理自 Python type()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。