You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类的输入校验应放置在何处?附当前__init__实现示例

将类的输入校验逻辑放在__init__方法中是否合理?

我目前将类的输入校验逻辑放置在__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__方法里是完全合理且符合Python最佳实践的,原因如下:

  • __init__作为类的初始化入口,负责实例的状态初始化,在这里做校验能确保实例从创建起就处于合法状态,避免后续调用类方法时才暴露参数问题。
  • 提前校验实现“快速失败”,能尽早终止非法实例的创建,减少不必要的资源消耗。

不过你的实现可以做几个优化,让代码更简洁、健壮:

  1. 简化类型判断:用not isinstance(...)替代isinstance(...) == False,更符合Python的语法习惯。
  2. 使用numpy内置方法检查数组维度和有序性:
    • 用ndim属性判断是否为一维数组,比len(shape)更直观。
    • 用np.diff结合np.all检查数组是否非降序,比手动循环更高效(numpy内置函数为C实现),代码也更简洁。
  3. 使用更具体的异常类型:替换通用的Exception为TypeError(类型不匹配时)、ValueError(数组维度错误、未排序时),方便调用者精准捕获和处理异常。
  4. 精准的错误提示:每个异常的提示信息对应具体问题,避免模糊表述。

优化后的代码示例:

import numpy as np

class MedianTwoSortedArrays:
    def __init__(self, sorted_array1, sorted_array2):
        # 输入类型校验
        if not isinstance(sorted_array1, np.ndarray) or not isinstance(sorted_array2, np.ndarray):
            raise TypeError("输入必须为np.ndarray类型")
        
        # 一维数组校验
        if sorted_array1.ndim != 1 or sorted_array2.ndim != 1:
            raise ValueError("输入必须是一维np.ndarray")
        
        # 非降序校验
        if not np.all(np.diff(sorted_array1) >= 0) or not np.all(np.diff(sorted_array2) >= 0):
            raise ValueError("输入数组必须是非降序排列")
        
        self.sorted_array1 = sorted_array1
        self.sorted_array2 = sorted_array2

内容的提问来源于stack exchange,提问作者Amazonian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:40:01