参数形式
- type(object)
- type(name, bases, dict)
Manual
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.
The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.
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 is copied to a standard dictionary to become the __dict__ attribute. For example, the following two statements create identical type objects:
>>>
>>> class X:
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
See also Type Objects.
直译
单参数时返回object的类型,返回值是一个类型对象,通常与object.__class__的返回对象相同。
对于测试对象类型,推荐isinstance()内建函数,因为它可以考虑到子类。
三个参数时返回一个新的类型对象,这本质上是类声明的动态形式。name字符串是类名,变成__name__属性;bases元组列出基类,变成__bases__属性;dict字典是包含类主体定义的命名空间,并拷贝到标准字典,变成__dict__属性。例如:以下两个声明创建了相同类型的对象:
>>>
>>> class X:
... a = 1
...
>>> X = type('X', (object,), dict(a=1))
详情见类型对象
实例
>>> type(object)
<class 'type'>
>>> type(type)
<class 'type'>
>>> type(dict)
<class 'type'>
>>> type(1)
<class 'int'>
>>> type(int)
<class 'type'>
>>> type('1')
<class 'str'>
>>> type(b'1')
<class 'bytes'>
>>> type(None)
<class 'NoneType'>
>>> type(True)
<class 'bool'>