內置函數type()
用于返回指定對象的類型,它還允許根據給定的參數返回新類型的對象。
**type(object)** #where object is whoes type needs to be return
**type(name, bases, dict)**
類型()參數:
取三個參數。type()
函數有助于在驗證失敗時打印參數的類型。
參數 | 描述 | 必需/可選 |
---|---|---|
名字 | 類名;成為 name 屬性 | 需要 |
基礎 | 列舉基類的元組;成為 bases 屬性 | 可選擇的 |
字典 | 字典,它是包含類主體定義的命名空間;成為 dict 屬性。 | 可選擇的 |
類型()返回值
如果傳遞了單個參數,其值與對象相同。class 實例變量。如果傳遞了三個參數,它會動態創建一個新類。
| 投入 | 返回值 | | 僅當對象 | 對象類型 | | If 3 參數 | 新的類型對象 |
Python 中type()
方法的示例
示例 1:如何獲取對象的類型
number_list = [3, 4]
print(type(number_list))
number_dict = {3: 'three', 4: 'four'}
print(type(number_dict))
class Foo:
a = 0
foo = Foo()
print(type(foo))
輸出:
< class 'list'>
< class 'dict'>
< class '__main__.Foo'>
示例 2:如何創建類型對象
obj1 = type('X', (object,), dict(a='Foo', b=12))
print(type(obj1))
print(vars(obj1))
class test:
a = 'Fo'
b = 15
obj2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(obj2))
print(vars(obj2))
輸出:
<class>{'a': 'Fo', 'b': 15, '__module__': '__main__', '__dict__': <attribute>, '__weakref__': <attribute>, '__doc__': None}
<class>{'a': 'Fo', 'b': 15, '__module__': '__main__', '__doc__': None}</class></attribute></attribute></class>