提高索引错误

Raising IndexError

所以我有一个 class 点,它在这里:

 class Point:

     def __init__(self,x,y):
         self.x = x
         self.y = y
     def __getitem__(self,index):
        self.coords = (self.x, self.y)
        if type(index) != str or type(index) != int:
            raise IndexError
        if index == 'x':
            return self.x
        elif index == 'y':
            return self.y
        elif index == 0:
            return self.coords[index]
        elif index == 1:
            return self.coords[index]

如果索引的类型不是 str 或 int,我应该引发 IndexError,但由于某种原因,如果我在函数的开头或结尾引发异常,它就不起作用。我应该在哪里提出异常?

你应该这样写检查语句:

type(index) != str and type(index) != int:

无论您的索引类型是什么,您当前的检查永远为真!

您的 if 陈述有误。尝试

if type(index) not in [str, int]

>>> index = {}
>>> type(index) not in [str, int]
True
>>> index = []
>>> type(index) not in [str, int]
True
>>> index = 0
>>> type(index) not in [str, int]
False
>>> index = '0'
>>> type(index) not in [str, int]
False
>>> 

你的问题出在这里:

if type(index) != str or type(index) != int:

如果是字符串,则不能是整数。反之,如果是整数,则不能是字符串。

因此,至少 一个 这些子条件将始终为真,因此 or 将它们设为真。

想想,我有一个水果,我想知道它既不是香蕉也不是苹果。

fruit   not banana OR not apple  not banana AND not apple
------  -----------------------  ------------------------
apple        T or F -> T               T and F -> F
banana       F or T -> T               F and T -> F
orange       T or T -> T               T and T -> T

而不是使用 or,您需要:

if type(index) != str and type(index) != int:

顺便说一句,除非您 需要 存储 coords 用于其他一些代码,否则您可以完全绕过该位,并使您的代码稍微清洁工:

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __getitem__(self,index):
        # Check type first.

        if type(index) != str and type(index) != int:
            raise IndexError

        # Return correct value for a correct index.

        if index == 'x' or index == 0:
            return self.x
        if index == 'y' or index == 1:
            return self.y

        # Index correct type but incorrect value.

        raise IndexError

该代码删除了(显然)多余的 coords,修复了类型检查,"minimised" if 语句为了清晰起见,并为以下情况添加了最终异常index 的类型可能是正确的,但它的 是错误的(例如 'z'42)。