Search code examples
python-3.xclasstry-catchinitraiserror

How to prevent a class to generate an object with an attribute used in an earlier instantiation, but not stop the code, in python


ids = []
class Car:
    def __init__(self, id_no, *args):
        if id_no in ids:
            raise Exception('Duplicate id')
        self.car_data = [id_no, *args]
        ids.append(id_no)
car_1 = Car('WBA123', 'BMW', '530')
car_2 = Car('WBA123', 'Ford', 'Mustang')
car_3 = Car('WDB567', 'Mercedes', 'S400')

So, the car_2 should not be created instead show a message, but the car_3 should be created.


Solution

  • If you want the code not to stop, you should catch the exception using try-catch block. But since you need to do this for creating every instance of the class, it's better to make a car builder function for it. Something like following:

    ids = []
    class Car:
        def __init__(self, id_no, *args):
            if id_no in ids:
                raise Exception('Duplicate id')
            self.car_data = [id_no, *args]
            ids.append(id_no)
    
    
    def build_car(*args):
        try:
            return Car(*args)
        except Exception as e:
            print(e)
    
    
    car_1 = build_car('WBA123', 'BMW', '530')
    car_2 = build_car('WBA123', 'Ford', 'Mustang')
    car_3 = build_car('WDB567', 'Mercedes', 'S400')