Python 开发 - type 函数(type 函数的基本使用、type 函数的返回值、type 函数与 isinstance 函数、type 函数元编程)
2026/6/2 18:16:40 网站建设 项目流程

一、type 函数的基本使用

  1. 检查基本类型
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'>
  1. 检查自定义类型
classMyClass:passobj=MyClass()print(type(obj))
# 输出结果 <class '__main__.MyClass'>

二、type 函数的返回值

  1. type 函数的返回值是一个类型对象
result=type(123)print(result)print(type(result))
# 输出结果 <class 'int'> <class 'type'>
  1. 使用__name__属性获取类型名称
result=type(123)print(result)print(result.__name__)
# 输出结果 <class 'int'> int

三、type 函数与 isinstance 函数

  1. 使用 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
  1. 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 函数元编程

  1. 动态创建类
MyClass=type('MyClass',(),{'x':42})obj=MyClass()print(obj.x)
# 输出结果 42
  1. 动态创建类,继承现有类
classBase:defshow(self):return"base class"Child=type('Child',(Base,),{'value':100})c=Child()print(c.show())print(c.value)
# 输出结果 base class 100
  1. 动态创建类,带方法
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

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询