type()函數(shù)根據(jù)所傳遞的參數(shù)返回對象的類型或返回新的類型對象。
type()函數(shù)具有兩種不同形式:
type(object) type(name, bases, dict)
如果將一個object傳遞給type(),該函數(shù)將返回其類型。
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))輸出結(jié)果
<class 'dict'> <class 'Foo'> <class '__main__.Foo'>
如果需要檢查對象的類型,則最好改用Python的isinstance()函數(shù)。這是因為isinstance()函數(shù)還會檢查給定的對象是否是子類的實例。
如果將三個參數(shù)傳遞給type(),它將返回一個新的type對象。
這三個參數(shù)是:
| 參數(shù) | 描述 |
|---|---|
| name | 班級名稱;成為__name__屬性 |
| bases | 列出基類的元組;成為__bases__屬性 |
| dict | 字典,它是包含類主體定義的名稱空間;成為__dict__屬性 |
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))輸出結(jié)果
<class 'type'>
{'b': 12, 'a': 'Foo', '__dict__': <attribute '__dict__' of 'X' objects>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'X' objects>}
<class 'type'>
{'b': 12, 'a': 'Foo', '__doc__': None}在程序中,我們使用了Python vars()函數(shù)來返回__dict__屬性。__dict__用于存儲對象的可寫屬性。
您可以根據(jù)需要輕松更改這些屬性。例如,如果您需要將的__name__屬性值o1更改為'Z',請使用:
o1.__name = 'Z'