Tutorial Study Image

Python type()

内置函数 type() 用于返回指定对象的类型,它也允许根据给定参数返回新的类型对象。


type(object) #where object is whoes type needs to be return
type(name, bases, dict) 

type() 参数

接受三个参数。当验证失败时,type() 函数有助于打印参数的类型。

参数 描述 必需/可选
name 一个类名;成为 __name__ 属性 必需
基类 一个元组,列出基类;成为 __bases__ 属性 可选
字典 一个字典,它是包含类体定义的命名空间;成为 __dict__ 属性。 可选

type() 返回值

如果只传递一个参数,其值与 object.__class__ 实例变量相同。如果传递三个参数,它将动态创建一个新类。

输入 返回值
如果只传递对象 对象的类型
如果传递 3 个参数 一个新的类型对象

Python 中 type() 方法的示例

示例 1:如何获取对象的类型


number_list = [3, 4]
print(type(number_list))

number_dict = {3: 'three', 4: 'four'}
print(type(number_dict))

class Foo:
    a = 0

foo = Foo()
print(type(foo))
 

输出

< class 'list'>
< class 'dict'>
< class '__main__.Foo'>

示例 2:如何创建类型对象


obj1 = type('X', (object,), dict(a='Foo', b=12))

print(type(obj1))
print(vars(obj1))

class test:
  a = 'Fo'
  b = 15
  
obj2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(obj2))
print(vars(obj2))
 

输出


{'a': 'Fo', 'b': 15, '__module__': '__main__', '__dict__': , '__weakref__': , '__doc__': None}

{'a': 'Fo', 'b': 15, '__module__': '__main__', '__doc__': None}