python type

基於2.7 版本ide

type 是內置函數,有兩種用法函數

class type(object)

With one argument, return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.

class type(name, bases, dict)

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the 
dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute. For example, the following two statements create identical type objects:

第一種用法,返回一個對象的類型,第二種用法,是構建一個類。要注意的是第二種用法,其實能夠猜出,經常使用的 class寫法是type 函數的一個語法糖ui

即,下面的兩個代碼等價spa

class A(object):
    v = 1

type('A', (object,), {'v': 1})

既然 type 能夠建立類,那麼可知 type 與 dict 等都是工廠函數。 也就是說,class 的類型,都是type 。 驗證以下:code

>>>> type(A)
<type 'type'>
相關文章
相關標籤/搜索