一、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'>检查自定义类型 class MyClass : pass obj= 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 函数进行类型检查 def check_type ( obj) : if type ( obj) == int : return "int" elif type ( obj) == float : return "float" elif type ( obj) == str : return "str" elif type ( obj) == list : return "list" elif type ( 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 dicttype 函数不能判断类型的继承关系,更推荐使用 isinstance 函数进行类型检查 class Parent : pass class Child ( Parent) : pass obj= 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动态创建类,继承现有类 class Base : def show ( self) : return "base class" Child= type ( 'Child' , ( Base, ) , { 'value' : 100 } ) c= Child( ) print ( c. show( ) ) print ( c. value) # 输出结果 base class 100动态创建类,带方法 def say_hello ( self) : return f"hello { self. name} " Person= type ( 'Person' , ( ) , { '__init__' : lambda self, name: setattr ( self, 'name' , name) , 'greet' : say_hello} ) p= Person( "tom" ) print ( p. greet( ) ) # 输出结果 hello tom