飞机订票系统简易代码
时间: 2024-03-10 22:42:20 浏览: 136
飞机订票系统是一个用于管理航班信息和乘客订票的系统。下面是一个简易的飞机订票系统的代码示例:
```python
class Flight:
def __init__(self, flight_number, departure, destination, date, capacity):
self.flight_number = flight_number
self.departure = departure
self.destination = destination
self.date = date
self.capacity = capacity
self.passengers = []
def add_passenger(self, passenger):
if len(self.passengers) < self.capacity:
self.passengers.append(passenger)
print(f"Passenger {passenger} added to flight {self.flight_number}")
else:
print(f"Flight {self.flight_number} is already full")
def get_available_seats(self):
return self.capacity - len(self.passengers)
class BookingSystem:
def __init__(self):
self.flights = {}
def add_flight(self, flight):
self.flights[flight.flight_number] = flight
def book_ticket(self, flight_number, passenger):
if flight_number in self.flights:
flight = self.flights[flight_number]
if flight.get_available_seats() > 0:
flight.add_passenger(passenger)
else:
print(f"No available seats on flight {flight_number}")
else:
print(f"Flight {flight_number} does not exist")
# 创建航班
flight1 = Flight("F001", "Beijing", "Shanghai", "2022-01-01", 100)
flight2 = Flight("F002", "Shanghai", "Beijing", "2022-01-02", 150)
# 创建订票系统
booking_system = BookingSystem()
# 添加航班到订票系统
booking_system.add_flight(flight1)
booking_system.add_flight(flight2)
# 订票
booking_system.book_ticket("F001", "Passenger A")
booking_system.book_ticket("F001", "Passenger B")
booking_system.book_ticket("F001", "Passenger C")
booking_system.book_ticket("F001", "Passenger D")
booking_system.book_ticket("F001", "Passenger E")
booking_system.book_ticket("F002", "Passenger F")
booking_system.book_ticket("F002", "Passenger G")
booking_system.book_ticket("F002", "Passenger H")
# 输出航班信息
print(f"Flight {flight1.flight_number} has {flight1.get_available_seats()} available seats")
print(f"Flight {flight2.flight_number} has {flight2.get_available_seats()} available seats")
```
这个简易的飞机订票系统代码示例包含了两个类:`Flight`和`BookingSystem`。`Flight`类表示一个航班,包含航班号、出发地、目的地、日期和容量等属性,以及添加乘客和获取可用座位数的方法。`BookingSystem`类表示订票系统,包含一个航班字典,可以添加航班和订票功能。
阅读全文