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]: True
In [11]: isinstance([],b)
Out[11]: False
使用type来动态创建类
2#################
In [12]: Pycon = type('Pycon',(object,),{'age':20})
In [13]: type(Pycon)
Out[13]: type
In [14]: Pycon.age
Out[14]: 20
In [15]: Pycon.__name__
Out[15]: 'Pycon'
3#################
In [20]: fun = lambda x: x+1
In [21]: ClaFun = type('ClaFun',(object,),{'add':fun })
In [22]: type(ClaFun.add)
Out[22]: instancemethod
In [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+1
In [30]: ClaFun = type('ClaFun',(object,),{'add':fun })
In [31]: a = ClaFun()
In [32]: a.add(3)
Out[32]: 4
这样就行了,根据条件动态创建类应该很有用处。