一、type 函数的基本使用
- 检查基本类型
print(type(123))print(type(3.14))print(type("hello"))print(type([1,2,3]))print(type({"a":1}))
# 输出结果 <class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'dict'>
- 检查自定义类型
classMyClass:passobj=MyClass()print(type(obj))
# 输出结果 <class '__main__.MyClass'>
二、type 函数的返回值
- type 函数的返回值是一个类型对象
result=type(123)print(result)print(type(result))
# 输出结果 <class 'int'> <class 'type'>
- 使用
__name__属性获取类型名称
result=type(123)print(result)print(result.__name__)
# 输出结果 <class 'int'> int
三、type 函数与 isinstance 函数
- 使用 type 函数进行类型检查
defcheck_type(obj):iftype(obj)==int:return"int"eliftype(obj)==float:return"float"eliftype(obj)==str:return"str"eliftype(obj)==list:return"list"eliftype(obj)==dict:return"dict"else:return"unknown"print(check_type(123))print(check_type(3.14))print(check_type("hello"))print(check_type([1,2,3]))print(check_type({"a":1}))
# 输出结果 int float str list dict
- type 函数不能判断类型的继承关系,更推荐使用 isinstance 函数进行类型检查
classParent:passclassChild(Parent):passobj=Child()print(type(obj)==Child)print(type(obj)==Parent)print(isinstance(obj,Child))print(isinstance(obj,Parent))
# 输出结果 True False True True
四、type 函数元编程
- 动态创建类
MyClass=type('MyClass',(),{'x':42})obj=MyClass()print(obj.x)
# 输出结果 42
- 动态创建类,继承现有类
classBase:defshow(self):return"base class"Child=type('Child',(Base,),{'value':100})c=Child()print(c.show())print(c.value)
# 输出结果 base class 100
- 动态创建类,带方法
defsay_hello(self):returnf"hello{self.name}"Person=type('Person',(),{'__init__':lambdaself,name:setattr(self,'name',name),'greet':say_hello})p=Person("tom")print(p.greet())
# 输出结果 hello tom