python type

基于2.7 版本

type 是内置函数,有两种用法

class type(object)

With one argument, 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.

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写法是type 函数的一个语法糖

即,下面的两个代码等价

class A(object):
    v = 1

type('A', (object,), {'v': 1})

既然 type 可以创建类,那么可知 type 与 dict 等都是工厂函数。 也就是说,class 的类型,都是type 。 验证如下:

>>>> type(A)
<type 'type'>

posted on 2019-04-25 22:03  kramer  阅读(119)  评论(0编辑  收藏  举报

导航