這什麼鬼 -- python3 type function

Posted by summer on September 22, 2021

語法

1
2
type(object)
type(name, bases, dict)
  • object - 物件
  • name - class 的名稱 (string)
  • bases - 繼承自何種類 (tuple)
  • dict - class 裡的屬性 (dict)

return 回傳物件型別,或回傳一個新的物件類型

說明

第一種用法十分常見,我們主要提第二種。

type(name, bases, dict),會回傳一個新的類型,來看看範例

範例

1
2
3
4
f=(type('Foo', (object,), {'bar':'BAR'}))
print(type(f))
print(f)
print(vars(f))

輸出

1
2
3
<class 'type'>
<class '__main__.Foo'>
{'bar': 'ae', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}