python type

基于2.7 版本ide

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

即,下面的两个代码等价spa

class A(object):
    v = 1

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

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

>>>> type(A)
<type 'type'>
相关文章
相关标签/搜索