Python 尝试排除混乱

Python Try and Except Confusion

我定义了一个 class 来包含点网格。我想对关键字参数 Grid_Points 执行错误检查,以确保用户为点数提供 float 或 int。如果他们没有指定任何内容,我希望出现错误。

class MyGrid:
    def __init__(self, Grid_Points=None, L=0.0, R=1.0):
    Grid = np.linspace(start=L, stop=R,num=Grid_Points, retstep=True)
    self.Grid = Grid[0]
    self.dx = Grid[1]

我实施了以下 tryexcept 子句。当我执行 TestGrid = MyGrid() 时,我收到一条错误消息 UnboundLocalError: local variable 'Grid' referenced before assignment.

我错过了什么?我认为尝试在 try 子句中执行 linspace 会导致异常(因为 Grid_Points 将等于 None)所以它应该转到 except 子句和打印出我指定的语句,然后终止代码的执行。我故意选择使用 Exception 这样它就可以捕捉到任何东西(一旦我开始使用它,我将使用更具体的东西)。但是代码似乎越过了 tryexcept 块。

class MyGrid:
    def __init__(self, Grid_Points=None, L=0.0, R=1.0):
    try:
        Grid = np.linspace(start=L, stop=R,num=Grid_Points, retstep=True)
    except Exception:
        print('Enter the number of grid points as either a float or int')
    self.Grid = Grid[0]
    self.dx = Grid[1]

您说您希望您的代码打印并终止 -- 但您忘记终止代码。您处理了异常,因此您的执行直接进行到其余代码:

self.Grid = Grid[0]
self.dx = Grid[1]

由于 Grid 未定义(linspace 调用中止),代码现在会出错并死在这里。您需要某种条件子句来处理这种情况,例如将 self 赋值移动到您的 try 块中:

class MyGrid:
    def __init__(self, Grid_Points=None, L=0.0, R=1.0):
      try:
        Grid = np.linspace(start=L, stop=R,num=Grid_Points, retstep=True)
        self.Grid = Grid[0]
        self.dx = Grid[1]
      except Exception:
        print('Enter the number of grid points as either a float or int')

更好的是,不要终止:只需 loop until you get a valid response.