我对这一点基本上是新手,所以如果答案是显而易见的,请提前道歉。对于一个学校作业(出于兴趣),我正在构建一个基本的汽车应用程序,它使用列表来存储汽车(对象),然后创建一个单独的列表来记录租来的汽车。你知道吗
租车流程运行得非常好,当我测试它时,它会将一辆车附加到我的rentedcars列表中,但是当我稍后在一个单独的函数中调用它(rentedcars)时,它会说它不能弹出一个空列表。你知道吗
我假设这是因为列表在一个函数中被修改,但是当我返回输出的修改后的列表并为函数分配一个变量以供以后使用时,它给了我一个错误,即在分配变量之前调用一个变量,并且给变量一个全局定义并不能解决它。你知道吗
下面是代码段,有人有什么想法吗?非常感谢。我在这里的论坛上看过几次这种问题,但是解决方案(至少在我尝试实现它们的时候)似乎没有解决它。你知道吗
函数rental_系统稍后调用,我刚刚展示了由于尺寸原因我遇到的问题,4种车型的所有列表都在initself下列出。等等和工作。你知道吗
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
问题是您正在通过
rental_system
方法将一个空列表传递给rented
方法。你知道吗您已经在
rental_system
方法中定义了rentedcars = []
,并且在不修改它的情况下尝试在rented
方法中从它弹出。你知道吗为什么不在类设计中添加
rented_cars
作为属性呢?你知道吗相关问题 更多 >
编程相关推荐