python的type函數

對於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

相關文章
相關標籤/搜索