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')
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')