Home > OS >  Error handling in the values in a class constructor
Error handling in the values in a class constructor

Time:08-24

I have a simple class defined as follows:

class SimpleClass():

    def __init__(self, n, m):
        self.n = n
        self.m = m

What is the best way to ensure that n and m are positive and m is less than n**2? Should I use an if-statement with a message? Is there any other particular pythonic way to handle this?

CodePudding user response:

Just use ordinary if statements.

class SimpleClass():

    def __init__(self, n, m):
        if n <= 0:
            raise ValueError('n must be positive')
        if m <= 0 or m >= n**2:
            raise ValueError('m must be between 0 and n**2')
        self.n = n
        self.m = m
  • Related