type()函数用于获取对象的类型,或者动态地创建一个新的类。

函数语法

该函数存在两种用法:

1. 获取对象的类型

type(object)

函数返回object的类型;

2. 动态创建类

type(name, bases, dict)

参数:

  • name:要创建类的名称;
  • bases:一个包含要继承父类的元组;
  • dict:一个包含属性和方法的字典;

函数返回一个新创建的类;

type() 函数示例

查看不同对象的类型:

print(type(123))       # <class 'int'>
print(type(3.14))      # <class 'float'>
print(type("Hello"))   # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type((1, 2, 3))) # <class 'tuple'>
print(type({"a": 1}))  # <class 'dict'>
print(type(True))      # <class 'bool'>

import math
print(type(math))      # <class 'module'>

传入三个参数时,可动态的创建类:

MyClass = type('MyClass', (), {'x': 10})

obj = MyClass()
print(obj.x)  # 10

创建带有方法的类:

def child_init(self):
    super(Child,self).__init__()
    self.y = 20

def say(self):
    print("hello!")

class Parent:
    def __init__(self):
        self.x = 10


Child = type('Child', (Parent,), {
    '__init__': child_init,
    'say': say
})

obj = Child()
print(obj.x) # 10
print(obj.y) # 20
obj.say()    # hello!