我对此大多是新手,如果答案对此非常明显,请提前道歉。对于学校作业(并且也感兴趣)我正在构建一种基本的汽车应用程序,它使用列表来存储汽车(对象),然后制作一个单独的列表来记录租用的汽车。
租赁过程完全正常,当我测试它时,它将汽车附加到我的租车列表中,但是当我稍后在一个单独的函数中调用它(租用汽车)时,它说它不能弹出一个空列表。
我认为这是因为列表在函数内被修改,但是当我返回输出的修改后的列表并为函数分配了一个变量供以后使用时,它给了我错误,我在调用它之前调用了一个变量,给变量一个全局定义并没有解决它。
代码段在下面,有人有什么想法吗?非常感谢。我在这里的论坛上已经多次看过这种问题,但解决方案(至少在我试图实现它们时)似乎没有解决它。
稍后会调用函数rental_system,我刚刚显示了因尺寸问题而导致的问题,4种类型汽车的所有列表都是在 init 下进行的自。等等和工作。
def rent(self, car_list, rented_cars, amount): # Process to rent a car function
if len(car_list) < amount:
print 'Not enough cars in stock' # Make sure enough cars in stock
return
total = 0
while total < amount:
carout = car_list.pop() # Pop last item from given car list and return it
rented_cars.append(carout) # Then append to a new list of rented cars that are now unavailable
total = total + 1
print 'Make: ' + carout.getMake()
print 'Colour: ' + carout.getColour()
print 'Engine Size(Cylinders): ' + carout.getEngineSize()
print 'You have rented ' + str(amount) + ' car(s)'
return rented_cars
def rented(self, car_list, rented_cars, amount): # Process for returning cars
total = 0
while total < amount:
carin = rented_cars.pop()
car_list.append(carin)
total = total + 1
print 'You have returned' +str(amount) + 'car(s)'
return rented_cars, car_list
def rental_system(self):
rentedcars = []
rented = raw_input('Are you returning or renting a car? Type either return/rent ')
if rented.lower() == 'return': # Return system
type = raw_input('Are you returning a petrol, electric, diesel or hybrid car? ')
amount = raw_input('How many would you like to return? ')
if type == 'petrol':
self.rented(self.petrolcars, rentedcars, amount)
elif type.lower() == 'diesel':
self.rented(self.dieselcars, rentedcars, amount)
elif type.lower() == 'hybrid':
self.rented(self.hybridcars, rentedcars, amount)
elif type.lower() == 'electric':
self.rented(self.electriccars, rentedcars, amount)
else:
print 'Error, please check your spelling'
return
if rented.lower() == 'rent':
answer = raw_input('What type of car would you like? Type: petrol/diesel/hybrid/electric ')
amount = int(raw_input('How many of that type of car?'))
if answer.lower() == 'petrol':
self.rent(self.petrolcars, rentedcars, amount)
elif answer.lower() == 'diesel':
self.rent(self.dieselcars, rentedcars, amount)
elif answer.lower() == 'hybrid':
self.rent(self.hybridcars, rentedcars, amount)
elif answer.lower() == 'electric':
self.rent(self.electriccars, rentedcars, amount)
else:
print 'Error, please check your spelling'
return
答案 0 :(得分:1)
问题是您通过rental_system
方法将空列表传递给rented
方法。
您已在rentedcars = []
方法中定义了rental_system
,并且未经修改就试图通过rented
方法从中弹出。
为什么不在课程设计中添加rented_cars
作为属性?