PYTHON:在哪里检查类的输入?

问题描述 投票:0回答:1

我应该在哪里检查类的输入。现在我将其放入

__init__
中,如下所示,但我不确定这是否正确。请参阅下面的示例

import numpy as np

class MedianTwoSortedArrays:
    def __init__(self, sorted_array1, sorted_array2):
        
        # check inputs --------------------------------------------------------
        # check if input arrays are np.ndarray's
        if isinstance(sorted_array1, np.ndarray) == False or \
            isinstance(sorted_array2, np.ndarray) == False:
            raise Exception("Input arrays need to be sorted np.ndarray's")
            
        # check if input arrays are 1D
        if len(sorted_array1.shape) > 1 or len(sorted_array2.shape) > 1:
            raise Exception("Input arrays need to be 1D np.ndarray's")
        
        # check if input arrays are sorted - note that this is O(n + m)
        for ind in range(0, len(sorted_array1)-1, 1):
            if sorted_array1[ind] > sorted_array1[ind + 1]:
                raise Exception("Input arrays need to be sorted")
        
        # end of input checks--------------------------------------------------
        
        self.sorted_array1 = sorted_array1
        self.sorted_array2 = sorted_array2
python python-3.x unit-testing exception input
1个回答
0
投票

验证

您通常有两次机会检查传递给构造函数表达式的参数:

  • __new__
    方法中,例如使用 creation
  • __init__
    方法中,例如使用初始化

您通常应该使用

__init__
进行初始化和验证。 仅在需要其独特特性的情况下才使用
__new__
。 所以,您的支票位于“正确”的位置。

如果您还想验证初始化后对实例变量的任何赋值,您可能会发现这个问题及其答案很有帮助。

异常类型

与主要问题无关:如果参数无效,则引发的异常应尽可能具体。 对于你的情况:

  • 如果参数没有正确的类型,请引发
    TypeError
    而不是仅仅
    Exception
  • 如果参数没有正确的值(或形状),请提高
    ValueError
    而不是仅仅
    Exception
© www.soinside.com 2019 - 2024. All rights reserved.