千锋教育-做有情怀、有良心、有品质的职业教育机构

手机站
千锋教育

千锋学习站 | 随时随地免费学

千锋教育

扫一扫进入千锋手机站

领取全套视频
千锋教育

关注千锋学习站小程序
随时随地免费学习课程

当前位置:首页  >  技术干货  > 用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.mobiletrain.org/

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