简体   繁体   English

验证Array参数的最大大小

[英]Validating max size of Array parameter

I'm practicing data structures and trying to make an Array class. 我正在练习数据结构并尝试制作Array类。 I'm also trying to validate the parameter. 我也在尝试验证参数。 Is there a better or more Pythonic way of initializing the class? 有没有更好或更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)]

Your code appears correct. 您的代码显示正确。 Beyond that it's a question of style. 除此之外,这是一个风格问题。 You correctly raise the right exceptions. 您正确提出了正确的例外。 You could potentially write some helper functions to simplify such validations if you are going to do a lot of them. 如果要进行很多验证,您可能会编写一些辅助函数来简化此类验证。

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

integer) 整数)

Then in your constructor 然后在您的构造函数中

assert_integer(i)

One disadvantage of such helper functions is that they will make the traceback longer. 这种辅助功能的一个缺点是它们会使回溯时间更长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM