全国旗舰校区

不同学习城市 同样授课品质

北京

深圳

上海

广州

郑州

大连

武汉

成都

西安

杭州

青岛

重庆

长沙

哈尔滨

南京

太原

沈阳

合肥

贵阳

济南

下一个校区
就在你家门口
+
当前位置:首页  >  技术干货

用Python的特性来切片无限生成器

发布时间:2023-11-07 03:43:32
发布人:xqq

注解推迟评估

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/

python培训

相关文章

Python字符串连接

Python字符串连接

2023-11-07
如何把awk脚本移植到Python

如何把awk脚本移植到Python

2023-11-07
数据科学中必须了解的Python核心库

数据科学中必须了解的Python核心库

2023-11-07
Python集合和时间复杂度

Python集合和时间复杂度

2023-11-07

最新文章

武汉新媒体行业公司排名

武汉新媒体行业公司排名

2023-11-01
武汉新媒体就业现状好吗

武汉新媒体就业现状好吗

2023-11-01
武汉全媒体行业发展现状及趋势

武汉全媒体行业发展现状及趋势

2023-10-31
武汉全媒体现状

武汉全媒体现状

2023-10-31
在线咨询 免费试学 教程领取