Reputation: 21
I have a program that simulates a bus in the form of a list and there is an ability to add passengers to the bus. I want to be able to set a max number of passengers, so that if the list exceeds 25 passengers I display a code stating that the bus is full.
Is it possible to set this limit in a list with Python.
Here is a snippet of the code:
#defining a class for the passenger list
class Bus:
passengers = []
number_of_passengers = 0
Upvotes: 0
Views: 400
Reputation: 555
You'd probably want to check the length of the list and then decide if you'll add a passenger or display a message. Something like so:
class Bus:
def __init__(self, max_number_of_passengers = 25):
self.passengers = []
self.max_number_of_passengers = max_number_of_passengers
def add_passenger(self, passenger):
if len(self.passengers) > self.max_number_of_passengers:
# display message
else:
self.passengers.append(passenger)
Upvotes: 1
Reputation: 717
You can use super
keyword for override lists.
class PassengerList(list):
limit = 0
def __init__(self, lim):
self.limit = lim
def append(self, item):
if len(self) >= self.limit:
raise Exception('Limit exceeded.')
super(PassengerList, self).append(item)
passengers = PassengerList(25)
passengers.append('abc')
You can set limit by parameter.
Upvotes: 3
Reputation: 16081
class Bus:
def __init__(self, limit=25):
self.passengers = []
self.bus_limit = limit
self.is_bus_full = False
def add_passenger(self):
if len(self.passengers) < self.bus_limit:
self.passengers.append(1) # add dummy values
else:
self.is_bus_full = True
def passenger_left(self):
self.passengers.pop()
def bus_status(self):
if self.is_bus_full:
return 'This bus is full'
else:
return 'This bus has vacant seats'
You can write something like this.
Upvotes: 0
Reputation: 9047
you can use a class
class Bus:
def __init__(self):
self.passengers = []
self.MAX_LIMIT = 25
def add_passenger(self, passenger):
if(len(self.passengers) <= self.MAX_LIMIT):
self.passengers.append(passenger)
else:
print('sorry bus is full')
def show_passengers(self):
print(self.passengers)
bus = Bus()
for i in range(26):
bus.add_passenger(i)
bus.add_passenger(26) #sorry bus is full
Upvotes: 0