【问题标题】:Raising IndexError提高索引错误
【发布时间】:2015-03-26 20:28:16
【问题描述】:

所以我有一个类Point,就在这里:

 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) ??你应该把它放在开头。

标签: class exception python-3.x


【解决方案1】:

你的问题在这里:

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

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

因此,这些子条件中至少有 一个 将始终为真,因此oring 他们将给真。

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

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 的多余使用,修复了类型检查,为清楚起见“最小化”了if 语句,并为index 的类型可能为正确但它的是错误的(例如'z'42)。

【讨论】:

  • @AJ,是的,你比我快了 6 秒,我想我不得不希望它是 最好的 答案,而不是最快的 :-)
  • @paxdiablo 最彻底的最佳答案:)
  • @paxdiablo,我可能比你快 6 秒,但你的 不错 :) +1
【解决方案2】:

您的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
>>> 

【讨论】:

    【解决方案3】:

    你应该这样写检查语句:

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

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

    【讨论】:

      猜你喜欢
      • 2017-09-18
      • 1970-01-01
      • 2015-04-28
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2015-11-17
      • 2016-08-28
      相关资源
      最近更新 更多