【问题标题】:Python raises exception 'generator' object does not support item assignment instead of 'generator' object is not subscriptablePython引发异常“生成器”对象不支持项目分配而不是“生成器”对象不可下标
【发布时间】:2013-12-06 18:56:27
【问题描述】:

我只是出于好奇才问这个问题。

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

# 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。

【问题讨论】:

    标签: python exception generator


    【解决方案1】:

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

    【讨论】:

    • 感谢您的快速回复! __setitem__ 是在 __getitem__ 之前调用的吗?我可以将a[0] 重写为 a.__getitem__(),将a[0] = 'puppy' 重写为a.__getitem__().__setitem__('puppy') 吗?还是我只是想错了?
    • @CodyPiersall: a[0] = 'puppy'a.__setitem__(0, 'puppy')。赋值时没有get操作。
    • 谢谢!正是我正在寻找的答案。给我2分钟,我会接受的。文档链接的奖励积分。
    猜你喜欢
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多