对于type,经常会用到的是判断类型,但是判断类型更推荐的一种方式是使用isinstance();但是很少会用到type的另外一个功能,生成一个新的类型,看官方解释:
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。
再举个demo:
django框架中的BaseManager
@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…
上一篇:python中的魔术方法__
下一篇:Python OOP实现