小数据池与编码新知

停博三天,今日续更!

一.小数据池

    代码块的概念了解一下?

    "A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c‘ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block. A code block is executed in an execution frame. A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block’s execution has completed."

    此处引用官方文档的描述,粗略翻译(前一部分),"python程序是由代码块组成的。一个代码块的文本作为python程序执行的单元。如下所列均为代码块:模块,函数,类。命令行(DOS终端,一行代码即为一个代码块)代码以及一个文件都属于代码块的范畴。eval()和exec()也是代码块。"

    引入小数据池:一种数据缓存机制,又称驻留机制。针对的数据类型包括:数字,字符串,布尔值(优先缓存)。

    对于数字: -5~256是会被加到小数据池中的(同一个代码块). 每次使用都是同一个对象.

    对于字符串:

      1.长度为0或1,自动缓存到小数据池

      2.长度大于1,但只包含"字母,数字,下划线"时缓存

      3.乘法得到的字符串:乘数为1, 仅包含数字, 字母, 下划线时会被缓存. 如果包含其他字符, 且长度<=1 也会被驻存;乘数大于1 . 仅包含数字, 字母, 下划线这个时候会被缓存. 但字符串长度不能大于20

      4.指定驻留. 我们可以通过sys模块中的intern()函数来指定要驻留的内容.

    小数据池和最开始的代码块有什么联系呢?

      执行同一个代码块时, 遇到初始化对象的命令时,他会将初始化的这个变量与值存储在一个字典中, 在遇到新的变量时, 会先在字典中查询记录, 如果有同样的记录,那么它会重复使用这个字典中的之前的这个值. 所以在你给出的例子中,文件执行时(同⼀一个代码块) 会把a, b两个变量量指向同⼀一个对象.否则,不同的代码块会先判断数据池中是否存在该数据,存在则指向同一个地址。

    通过id()可以查看数据的存储地址。使用"=="(数据内容是否一致)和"is"(存储地址是否一致)可进一步判断。

二.编码新知

    在python3的内存中,程序运行阶段,默认使用的是Unicode编码,但由于内存占用方面的浪费问题,数据的传输与存储,往往需要采用编码形式,转存为"utf-8"或者"gbk“格式,经过编码后的数据以bytes类型进行存储(英文编码前后不发生变化)。

    编码:encode()    针对字符串类型数据

    解码:decode() 针对bytes类型数据

    注:不同的编码之间不能随意转换. 

  12.4,晚上好!     

posted on 2018-12-04 20:06  地球上的小东西  阅读(108)  评论(0编辑  收藏  举报