Class 提升索引器
我有一个课堂要点,在这里:Class 提升索引器,class,exception,python-3.x,Class,Exception,Python 3.x,我有一个课堂要点,在这里: 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 IndexErr
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,但是由于某种原因,如果我在函数的开头或结尾引发异常,它就不起作用。我应该在何处引发异常?您应该这样写check语句:
type(index) != str and type(index) != int:
无论您的索引类型是什么,您当前的检查都永远正确 如果语句有误,您的
。试一试
if type(index) not in [str, int]
你的问题在于:
if type(index) != str or type(index) != int:
如果是字符串,则不能是整数。相反,如果它是整数,就不能是字符串
因此,这些子条件中至少有一个将始终为真,因此或对它们进行运算将得到真
想想看,我有一个水果,我想知道它既不是香蕉也不是苹果
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
您需要:
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
语句以保持清晰,并为索引的类型可能正确但其值错误的情况(例如'z'
或42
)添加了一个最终例外情况(如果type(index)!=str和type(index)!=int)??你应该把它放在开头。@A.J.,是的,你赢了我6秒,我想我只能希望它是最好的答案,而不是最快的:-)@paxdiablo最好的答案是最彻底的:)@paxdiablo,我可能赢了你6秒,但你的很好:)+1
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