新聞中心
了解更多關(guān)于這個(gè)和其他兩個(gè)未被充分利用但仍然有用的 Python 特性。
創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比大理州網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式大理州網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋大理州地區(qū)。費(fèi)用合理售后完善,10年實(shí)體公司更值得信賴。
這是關(guān)于 Python 3.x 首發(fā)特性系列文章的第八篇。Python 3.7 于 2018 年首次發(fā)布,盡管它已經(jīng)發(fā)布了幾年,但它引入的許多特性都未被充分利用,而且相當(dāng)酷。下面是其中的三個(gè)。
注解推遲評(píng)估
在 Python 3.7 中,只要激活了正確的 __future__ 標(biāo)志,注解在運(yùn)行時(shí)就不會(huì)被評(píng)估:
from __future__ import annotationsdef another_brick(wall: List[Brick], brick: Brick) -> Education:pass
another_brick.__annotations__
{'wall': 'List[Brick]', 'brick': 'Brick', 'return': 'Education'}
它使遞歸類型(指向自己的類)和其他有趣的事情成為了可能。然而,這意味著如果你想做自己的類型分析,你需要明確地使用 ast。
import astraw_type = another_brick.__annotations__['wall'][parsed_type] = ast.parse(raw_type).body
subscript = parsed_type.valuef"{subscript.value.id}[{subscript.slice.id}]"
'List[Brick]'
itertools.islice 支持 index
Python 中的序列切片長(zhǎng)期以來(lái)一直接受各種 類 int 對(duì)象(具有 __index__() 的對(duì)象)作為有效的切片部分。然而,直到 Python 3.7,itertools.islice,即核心 Python 中對(duì)無(wú)限生成器進(jìn)行切片的唯一方法,才獲得了這種支持。
例如,現(xiàn)在可以用 numpy.short 大小的整數(shù)來(lái)切片無(wú)限生成器:
import numpyshort_1 = numpy.short(1)short_3 = numpy.short(3)short_1, type(short_1)
(1, numpy.int16)
import itertoolslist(itertools.islice(itertools.count(), short_1, short_3))
[1, 2]
functools.singledispatch() 注解注冊(cè)
如果你認(rèn)為 singledispatch 已經(jīng)很酷了,你錯(cuò)了?,F(xiàn)在可以根據(jù)注解來(lái)注冊(cè)了:
import attrimport mathfrom functools import singledispatch@attr.s(auto_attribs=True, frozen=True)class Circle:radius: float@attr.s(auto_attribs=True, frozen=True)class Square:side: float@singledispatchdef get_area(shape):raise NotImplementedError("cannot calculate area for unknown shape",shape)@get_area.registerdef _get_area_square(shape: Square):return shape.side ** 2@get_area.registerdef _get_area_circle(shape: Circle):return math.pi * (shape.radius ** 2)get_area(Circle(1)), get_area(Square(1))
(3.141592653589793, 1)
歡迎來(lái)到 2017 年
Python 3.7 大約是四年前發(fā)布的,但是在這個(gè)版本中首次出現(xiàn)的一些特性非常酷,而且沒有得到充分利用。如果你還沒使用,那么將它們添加到你的工具箱中。
新聞標(biāo)題:用這個(gè)Python3.7的特性來(lái)切片無(wú)限生成器
文章源于:http://www.5511xx.com/article/dhisdci.html


咨詢
建站咨詢

