按照Python官網(wǎng)上的計(jì)劃,Python3.6正式版期望在2016-12-16號(hào)發(fā)布,也就是這周五。從去年的5月份開(kāi)始,Python3.6版本就已經(jīng)動(dòng)手開(kāi)發(fā)了,期間也斷斷續(xù)續(xù)的發(fā)布了4個(gè)Alpha版,4個(gè)Beta版,以及一個(gè)Candidate版本。
作為一個(gè)Python愛(ài)好者,很期待新版本的發(fā)布,也希望能第一時(shí)間嘗試一下新特性。本文就根據(jù)Python官網(wǎng)文章What's New In Python 3.6,簡(jiǎn)單介紹下Python3.6中的一些新特性。
如果你想嘗試Python3.6,又不想破壞本機(jī)的Python環(huán)境,建議使用Docker。如果不會(huì)使用Docker,可以看下這里 //www.jb51.net/article/94198.htm
新的語(yǔ)法特性
1、格式化字符串(Formatted string literals)
即在普通字符串前添加 f 或 F 前綴,其效果類似于str.format()。比如
name = "Fred"print(f"He said his name is {name}.") # 'He said his name is Fred.'
其效果相當(dāng)于:
print("He said his name is {name}.".format(**locals()))
此外,此特性還支持嵌套字段,比如:
width = 10precision = 4value = decimal.Decimal("12.34567")print(f"result: {value:{width}.{precision}}") #'result: 12.35'
2、變量聲明語(yǔ)法(variable annotations)
即從Python3.5開(kāi)始就有的Typehints。在Python3.5中,是這么使用的:
from typing import Listdef test(a: List[int], b: int) -> int: return a[0] + bprint(test([3, 1], 2))
這里的語(yǔ)法檢查只在編輯器(比如Pycharm)中產(chǎn)生,在實(shí)際的使用中,并不進(jìn)行嚴(yán)格檢查。
在Python3.6中,引入了新的語(yǔ)法:
from typing import List, Dictprimes: List[int] = []captain: str # 此時(shí)沒(méi)有初始值class Starship: stats: Dict[str, int] = {}
3、數(shù)字的下劃線寫法(Underscores in Numeric Literals)
即允許在數(shù)字中使用下劃線,以提高多位數(shù)字的可讀性。
a = 1_000_000_000_000_000 # 1000000000000000b = 0x_FF_FF_FF_FF # 4294967295
除此之外,“字符串格式化”也支持“_”選項(xiàng),以打印出更易讀的數(shù)字字符串:
'{:_}'.format(1000000) # '1_000_000''{:_x}'.format(0xFFFFFFFF) # 'ffff_ffff'
4、異步生成器(Asynchronous Generators)
在Python3.5中,引入了新的語(yǔ)法 async 和 await 來(lái)實(shí)現(xiàn)協(xié)同程序。但是有個(gè)限制,不能在同一個(gè)函數(shù)體內(nèi)同時(shí)使用 yield 和 await,在Python3.6中,這個(gè)限制被放開(kāi)了,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 語(yǔ)法。
新聞熱點(diǎn)
疑難解答
圖片精選