加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 异步的语义等价于

发布时间:2020-12-16 22:47:15 所属栏目:Python 来源:网络整理
导读:从Python 3.5中相对于async语法的文档中,我收集到它是为了迭代一个等待的迭代器而引入的. 尽管如此,我仍然没有按照描述的语义等价物获得: iter = (ITER)iter = type(iter).__aiter__(iter)running = Truewhile running: try: TARGET = await type(iter).__a

从Python 3.5中相对于async语法的文档中,我收集到它是为了迭代一个等待的迭代器而引入的.

尽管如此,我仍然没有按照描述的语义等价物获得:

iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
    try:
        TARGET = await type(iter).__anext__(iter)
    except StopAsyncIteration:
        running = False
    else:
       BLOCK
else:
    BLOCK2 

什么是iter = type(iter).__ aiter __(iter)在做什么?为什么有必要?

最佳答案
python中的魔术方法,例如__add __,总是looked up on the class.例如,len(foo)实际上会调用resolve来键入(foo).__ len __(foo).这意味着如果在foo上定义了__len__,它将永远不会使用foo .__ len__. [1]

由于__aiter__是一种神奇的方法,因此它总是被查找为类型(foo).__ aiter __(foo).

查找示例:

class Thingy(object):
  def __len__(self):
    return 10

lengthy_thingy = Thingy()
lengthy_thingy.__len__ = lambda self: 20

print(len(lengthy_thingy))  # gives `10`
print(lengthy_thingy.__len__(lengthy_thingy))  # gives `20` instead
print(type(lengthy_thingy).__len__(lengthy_thingy))  # gives `10` as for using `len`

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读