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')
如果你想让代码不停止,你应该使用以下方法捕获异常 try-catch
块。但是由于创建该类的每一个实例都需要这样做,所以最好为它做一个造车功能。像下面这样。
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')