python type
type(object)
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.
返回對象的類型。返回的對象是一個type類型。推薦使用isinstance()來檢測一個對象的類型。
With three arguments, type() functions as a constructor as detailed below.
使用3個參數的時候,type()方法可以作為一個構造器。
type(name, bases, dict)
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:
返回一個新的類型對象。從本質來說是一種類的動態聲明。
name 參數是class的名稱,也是 __name__屬性的值
bases 元組列出了這個類的父類,成為了__bases__屬性的值
dict 包含了類體的定義,成為 __dict__屬性
下面是一個案例:
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
#----------------------------------------------------------------------------
也就是說這個type可以在運行時產生我們定製的類
自己來試一試:
小例
使用type來判斷物件類型是否相同:
1 ###############In [8]: a = '1'In [9]: b = type(a)In [10]: isinstance('3',b)Out[10]: TrueIn [11]: isinstance([],b)Out[11]: False使用type來動態建立類2#################In [12]: Pycon = type('Pycon',(object,),{'age':20})In [13]: type(Pycon)Out[13]: typeIn [14]: Pycon.ageOut[14]: 20In [15]: Pycon.__name__Out[15]: 'Pycon'3#################In [20]: fun = lambda x: x+1In [21]: ClaFun = type('ClaFun',(object,),{'add':fun })In [22]: type(ClaFun.add)Out[22]: instancemethodIn [26]: a = ClaFun()In [27]: a.add(3)---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-27-bebdff6e9b30> in <module>()----> 1 a.add(3)TypeError: <lambda>() takes exactly 1 argument (2 given)#---但是調用不行,缺少了一個self參數4#################In [29]: fun = lambda self,x: x+1In [30]: ClaFun = type('ClaFun',(object,),{'add':fun })In [31]: a = ClaFun()In [32]: a.add(3)Out[32]: 4
這樣就行了,根據條件動態建立類應該很有用處。