对于type,常常会用到的是判断类型,可是判断类型更推荐的一种方式是使用isinstance();可是不多会用到type的另一个功能,生成一个新的类型,看官方解释:django
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 X(object): ... a = 1 ... >>> X = type('X', (object,), dict(a=1))
这样就能够产生一个新的类型X。ide
再举个demo:
django框架中的BaseManagerspa
@classmethod def from_queryset(cls, queryset_class, class_name=None): if class_name is None: class_name = '%sFrom%s' % (cls.__name__, queryset_class.__name__) class_dict = { '_queryset_class': queryset_class, } class_dict.update(cls._get_queryset_methods(queryset_class)) return type(class_name, (cls,), class_dict)
over...code