python标准库介绍——13 types 模块详解
2017-10-28 22:16
716 查看
== types 模块== ``types`` 模块包含了标准解释器定义的所有类型的类型对象, 如 [Example 1-86 #eg-1-86] 所示. 同一类型的所有对象共享一个类型对象. 你可以使用 ``is`` 来检查一个对象是不是属于某个给定类型. ====Example 1-86. 使用 types 模块====[eg-1-86] ``` File: types-example-1.py import types def check(object): print object, if type(object) is types.IntType: print "INTEGER", if type(object) is types.FloatType: print "FLOAT", if type(object) is types.StringType: print "STRING", if type(object) is types.ClassType: print "CLASS", if type(object) is types.InstanceType: print "INSTANCE", print check(0) check(0.0) check("0") class A: pass class B: pass check(A) check(B) a = A() b = B() check(a) check(b) *B*0 INTEGER 0.0 FLOAT 0 STRING A CLASS B CLASS <A instance at 796960> INSTANCE <B instance at 796990> INSTANCE*b* ``` 注意所有的类都具有相同的类型, 所有的实例也是一样. 要测试一个类或者实例所属的类, 可以使用内建的 ``issubclass`` 和 ``isinstance`` 函数. ``types`` 模块在第一次引入的时候会破坏当前的异常状态. 也就是说, 不要在异常处理语句块中导入该模块 (//或其他会导入它的模块//) .
相关文章推荐
- python标准库介绍——27 random 模块详解
- python标准库介绍——19 mmap 模块详解
- python标准库介绍——28 md5 模块详解
- python标准库介绍——28 sha 模块详解
- python标准库介绍——2 os.path模块详解
- python标准库介绍——20 cStringIO 模块详解
- python标准库介绍——3 stat 模块详解
- python标准库介绍——31 threading 模块详解
- python标准库介绍——22 UserList 模块详解
- python标准库介绍——5 re模块详解
- python标准库介绍——15 fileinput 模块详解
- python标准库介绍——24 traceback 模块详解
- python标准库介绍——23 UserString 模块详解
- python标准库介绍——30 code 模块详解
- python标准库介绍——35 pipes 模块详解
- python标准库介绍——25 errno 模块详解
- python标准库介绍——7 cmath 模块详解
- python标准库介绍——36 popen2 模块详解
- python标准库介绍——26 getopt 模块详解
- python标准库介绍——37 signal 模块详解