我应该在哪里检查类的输入。现在我将其放入
__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
您通常有两次机会检查传递给构造函数表达式的参数:
您通常应该使用
__init__
进行初始化和验证。 仅在需要其独特特性的情况下才使用 __new__
。 所以,您的支票位于“正确”的位置。
如果您还想验证初始化后对实例变量的任何赋值,您可能会发现这个问题及其答案很有帮助。
与主要问题无关:如果参数无效,则引发的异常应尽可能具体。 对于你的情况:
TypeError
而不是仅仅 Exception
。ValueError
而不是仅仅 Exception
。