gpt4 book ai didi

Python raises exception 'generator' object does not support item assignment 而不是 'generator' object is not subscriptable

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:07 27 4
gpt4 key购买 nike

这是我出于好奇才问的问题。

我回答了this question关于生成器,引发的异常让我感到惊讶。我希望这两个都给出相同的异常(exception):

# Create a lame generator
a = (x for x in range(5))

# This raises a TypeError with the message "'generator' object is not subscriptable"
# I completely expected this.
a[0]

# Why doesn't this give the same message?
# This raises a TypeError with the message "'generator' object does not support item assignment"
# which is (I think) the exception raised when trying to assign to an immutable object.
a[0] = 2

我希望他们都引发一个 TypeError 并显示消息“'generator' object is not subscriptable”,因为它似乎更重要。为什么要在尝试访问元素时已经引发异常的情况下给出无法分配的消息?

不确定这是否相关,但我使用的是 Python 3.3。

最佳答案

这两个操作调用不同的方法;访问下标会调用 __getitem__() ,而设置下标会调用 __setitem__() .每个都会引发不同的异常,因为每个在概念上都是不同的操作。

关于Python raises exception 'generator' object does not support item assignment 而不是 'generator' object is not subscriptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20135643/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com