【发布时间】:2025-12-12 23:55:02
【问题描述】:
我最近听说在 python 中使用语句处理异常的可能性
try:
和
except WhateverError:
我只是想知道在定义下一个类时使用它是否是个好主意。 它应该代表一个地形。矩阵的每个数字代表它的一个坐标,数字就是该坐标的高度。
class base_terreny(object):
# create default mxn terrain #
def __init__(self, rows, columns):
self.rows=rows
self.columns=columns
self.terrain=[[0]*columns for _ in range(rows)]
def __getitem__(self, pos): #return height of coordinate
try:
return self.terrain[pos[1]][pos[0]]
except (IndexError,TypeError):
return 0
def __setitem__(self, pos, h): #set height
try:
self.terrain[pos[1]][pos[0]]=h
except (IndexError,TypeError):
return None
或者这样做会更好:
if pos[0]<=self.columns and pos[1]<=self.rows:
self.terrain[pos[1]][pos[0]]=h
【问题讨论】:
-
你的语法不正确;要捕获多个异常,请将它们指定为元组:
except (IndexError, TypeError):。 -
在这种情况下,使用异常处理程序;出界将是个例外。
标签: python class try-catch except