验证Array参数的最大大小

时间:2017-09-21 22:03:29

标签: python arrays validation

我正在练习数据结构并尝试创建一个Array类。我也试图验证参数。是否有更好或更多的Pythonic方法来初始化课程?

class Array:
    def __init__(self, max_size):
        if not isinstance(max_size, int):
            raise TypeError(f"'{type(max_size).__name__}' object cannot be interpreted as an integer")
        elif max_size < 0:
            raise ValueError(f'Please pass in a non-negative integer')
        else:
            self.maxsize = max_size
            self.items = [None for _ in range(max_size)]

1 个答案:

答案 0 :(得分:1)

您的代码显示正确无误。除此之外,这是一个风格问题。你正确地提出了正确的例外。如果你要做很多这样的验证,你可以编写一些辅助函数来简化这些验证。

def assert_integer(i):
    if not isinstance(i, int):
        raise TypeError(i.__class__.__name__+' could not be interpreted as an 

整数)

然后在你的构造函数

assert_integer(i)

这种辅助函数的一个缺点是它们会使回溯更长。