Search code examples
pythonpython-3.xpython-3.9python-class

suspending negative values during object definition (Python)


Since Im refreshing my python skills at the moment I stumbled across the problem of suspending (for example negative attribute values) during object definition.

class Motorcycle:
    def __init__(self,make,displacement):
        self.make=make            
        self.displacement=displacement

it would make sense to suspend negative values for the displacement attribute(and ask as long for another value until a positive value is entered), but I can't find a way to do that during object definition.


Solution

  • You can raise an exception in case you are getting an negative value. You should also add info in the docstring indicating you want positive values for displacement:

    class Motorcycle:
        def __init__(self, make, displacement):
            if displayment < 0:
                raise ValueError('Value for displacement must be non-negative')
    
            self.make=make            
            self.displacement=displacement