我想创建我的班车的实例。如何从列表中为每个x数量的汽车中的参数设置?
argument_list = ['h','2','2','0','v','2','0','0'........etc]
car1 = car('h','2','2','0')
car2 = car('v','2','0','0')
car3 = car(............etc)
为每一辆车做这件事会非常糟糕:
car1 = car(*coordinate_list[0:4])
car2 = car(*coordinate_list[4:8])
答案 0 :(得分:0)
你可以用for循环和全局变量完成这个。
class Car:
def __init__(self, *args, **kwargs):
print(args, kwargs)
self.attr1 = args[0]
self.attr2 = args[1]
self.attr3 = args[2]
self.attr4 = args[3]
argument_list = list(range(32)) #enough arguments for 8 cars
# the // operator guarantees integer division
num_cars = len(argument_list)//4
car_list = []
for i in range(num_cars-1):
# [i*4:(i+1)*4] will grab 4 items at a time from argument list
# the asterisk before it *argument_list[i*4:(i+1)*4] unpacks the list so they can be arguments for init
car_list.append(Car(*argument_list[i*4:(i+1)*4]))
for car in car_list:
print(car.attr1, car.attr2, car.attr3, car.attr4)
for i, car in enumerate(car_list):
# accesses global variables and adds whatever variable we want by name
globals()['car' + str(i)] = car
print(car1.attr1)
print(car2.attr2)