源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python3.6正式版新特性预览

  • 时间:2021-10-09 14:15 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python3.6正式版新特性预览
按照Python官网上的计划,Python3.6正式版期望在2016-12-16号发布,也就是这周五。从去年的5月份开始,Python3.6版本就已经动手开发了,期间也断断续续的发布了4个Alpha版,4个Beta版,以及一个Candidate版本。 作为一个Python爱好者,很期待新版本的发布,也希望能第一时间尝试一下新特性。本文就根据Python官网文章[url=https://docs.python.org/3.6/whatsnew/3.6.html]What's New In Python 3.6[/url],简单介绍下Python3.6中的一些新特性。 如果你想尝试Python3.6,又不想破坏本机的Python环境,建议使用Docker。如果不会使用Docker,可以看下这里  [url=http://www.1sucai.cn/article/94198.htm]http://www.1sucai.cn/article/94198.htm[/url] [b]新的语法特性[/b] 1、格式化字符串(Formatted string literals) 即在普通字符串前添加 f 或 F 前缀,其效果类似于str.format()。比如
name = "Fred"
print(f"He said his name is {name}.") # 'He said his name is Fred.'
其效果相当于: [code]print("He said his name is {name}.".format(**locals()))[/code] 此外,此特性还支持嵌套字段,比如:
width = 10
precision = 4
value = decimal.Decimal("12.34567")
print(f"result: {value:{width}.{precision}}") #'result:   12.35'

2、变量声明语法(variable annotations) 即从Python3.5开始就有的Typehints。在Python3.5中,是这么使用的:
from typing import List

def test(a: List[int], b: int) -> int:
  return a[0] + b

print(test([3, 1], 2))

这里的语法检查只在编辑器(比如Pycharm)中产生,在实际的使用中,并不进行严格检查。 在Python3.6中,引入了新的语法:
from typing import List, Dict

primes: List[int] = []
captain: str  # 此时没有初始值

class Starship:
  stats: Dict[str, int] = {}

3、数字的下划线写法(Underscores in Numeric Literals) 即允许在数字中使用下划线,以提高多位数字的可读性。
a = 1_000_000_000_000_000    # 1000000000000000
b = 0x_FF_FF_FF_FF       # 4294967295
除此之外,“字符串格式化”也支持“_”选项,以打印出更易读的数字字符串:
'{:_}'.format(1000000)     # '1_000_000'
'{:_x}'.format(0xFFFFFFFF)   # 'ffff_ffff'

4、异步生成器(Asynchronous Generators) 在Python3.5中,引入了新的语法 async 和 await 来实现协同程序。但是有个限制,不能在同一个函数体内同时使用 yield 和 await,在Python3.6中,这个限制被放开了,Python3.6中允许定义异步生成器:
async def ticker(delay, to):
"""Yield numbers from 0 to *to* every *delay* seconds."""
  for i in range(to):
    yield i
    await asyncio.sleep(delay)

5、异步解析器(Asynchronous Comprehensions) 即允许在列表list、集合set 和字典dict 解析器中使用 async for 或 await 语法。
result = [i async for i in aiter() if i % 2]
result = [await fun() for fun in funcs if await condition()]

[b]新增加模块[/b] Python标准库(The Standard Library)中增加了一个新的模块:secrets。该模块用来生成一些安全性更高的随机数,以用来管理数据,比如passwords, account authentication, security tokens, 以及related secrets等。具体用法可参考官方文档:secrets [b]其他新特性[/b] 1、新的 PYTHONMALLOC 环境变量允许开发者设置内存分配器,以及注册debug钩子等。 2、asyncio模块更加稳定、高效,并且不再是临时模块,其中的API也都是稳定版的了。 3、typing模块也有了一定改进,并且不再是临时模块。 4、datetime.strftime 和 date.strftime 开始支持ISO 8601的时间标识符%G, %u, %V。 5、hashlib 和 ssl 模块开始支持OpenSSL1.1.0。 6、hashlib模块开始支持新的hash算法,比如BLAKE2, SHA-3 和 SHAKE。 7、Windows上的 filesystem 和 console 默认编码改为UTF-8。 8、json模块中的 json.load() 和 json.loads() 函数开始支持 binary 类型输入。 9、....... 还有很多其他特性,但在平时工作中能用到的大概就这么多了。有兴趣的读者可以直接参考官方文档:[url=https://docs.python.org/3.6/whatsnew/3.6.html]What's New In Python 3.6[/url]
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部