国产一区二区精品-国产一区二区精品久-国产一区二区精品久久-国产一区二区精品久久91-免费毛片播放-免费毛片基地

千鋒教育-做有情懷、有良心、有品質的職業教育機構

手機站
千鋒教育

千鋒學習站 | 隨時隨地免費學

千鋒教育

掃一掃進入千鋒手機站

領取全套視頻
千鋒教育

關注千鋒學習站小程序
隨時隨地免費學習課程

當前位置:首頁  >  技術干貨  > 用Python的特性來切片無限生成器

用Python的特性來切片無限生成器

來源:千鋒教育
發布人:xqq
時間: 2023-11-07 03:43:32 1699299812

注解推遲評估

Python3.7中,只要激活了正確的__future__標志,注解在運行時就不會被評估:

from__future__importannotations

defanother_brick(wall:List[Brick],brick:Brick)->Education:

pass

another_brick.__annotations__

{'wall':'List[Brick]','brick':'Brick','return':'Education'}

它使遞歸類型(指向自己的類)和其他有趣的事情成為了可能。然而,這意味著如果你想做自己的類型分析,你需要明確地使用ast。

importast

raw_type=another_brick.__annotations__['wall']

[parsed_type]=ast.parse(raw_type).body

subscript=parsed_type.value

f"{subscript.value.id}[{subscript.slice.id}]"

'List[Brick]'

itertools.islice支持index

Python中的序列切片長期以來一直接受各種類int對象(具有__index__()的對象)作為有效的切片部分。然而,直到Python3.7,itertools.islice,即核心Python中對無限生成器進行切片的唯一方法,才獲得了這種支持。

例如,現在可以用numpy.short大小的整數來切片無限生成器:

importnumpy

short_1=numpy.short(1)

short_3=numpy.short(3)

short_1,type(short_1)

(1,numpy.int16)

importitertools

list(itertools.islice(itertools.count(),short_1,short_3))

[1,2]

functools.singledispatch()注解注冊

如果你認為singledispatch已經很酷了,你錯了。現在可以根據注解來注冊了:

importattr

importmath

fromfunctoolsimportsingledispatch

@attr.s(auto_attribs=True,frozen=True)

classCircle:

radius:float

@attr.s(auto_attribs=True,frozen=True)

classSquare:

side:float

@singledispatch

defget_area(shape):

raiseNotImplementedError("cannotcalculateareaforunknownshape",

shape)

@get_area.register

def_get_area_square(shape:Square):

returnshape.side**2

@get_area.register

def_get_area_circle(shape:Circle):

returnmath.pi*(shape.radius**2)

get_area(Circle(1)),get_area(Square(1))

(3.141592653589793,1)

以上內容為大家介紹了用Python的特性來切片無限生成器,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。http://www.kei0345678.cn/

tags: python培訓
聲明:本站稿件版權均屬千鋒教育所有,未經許可不得擅自轉載。
10年以上業內強師集結,手把手帶你蛻變精英
請您保持通訊暢通,專屬學習老師24小時內將與您1V1溝通
免費領取
今日已有369人領取成功
劉同學 138****2860 剛剛成功領取
王同學 131****2015 剛剛成功領取
張同學 133****4652 剛剛成功領取
李同學 135****8607 剛剛成功領取
楊同學 132****5667 剛剛成功領取
岳同學 134****6652 剛剛成功領取
梁同學 157****2950 剛剛成功領取
劉同學 189****1015 剛剛成功領取
張同學 155****4678 剛剛成功領取
鄒同學 139****2907 剛剛成功領取
董同學 138****2867 剛剛成功領取
周同學 136****3602 剛剛成功領取
相關推薦HOT