class ParkingSpot: def init(self, spot_id, status='Available'): self.spot_id = spot_id self.status = status def str(self): return f'Spot ID: {self.spot_id} Status: {self.status}' class ParkingLot: def init(self, num_spots): self.spots = [ParkingSpot(i) for i in range(1, num_spots+1)] def park_vehicle(self, spot_id): spot = self.spots[spot_id-1] if spot.status == 'Available': spot.status = 'Occupied' print(f'Spot {spot_id} is now occupied.') else: print(f'Spot {spot_id} is already occupied.') def release_spot(self, spot_id): spot = self.spots[spot_id-1] if spot.status == 'Occupied': spot.status = 'Available' print(f'Spot {spot_id} is now available.') else: print(f'Spot {spot_id} is already available.') def display_spots(self): for spot in self.spots: print(spot)具体解释代码意思
时间: 2023-06-02 15:08:33 浏览: 104
python使用 __init__初始化操作简单示例
5星 · 资源好评率100%
这段代码定义了一个停车场类(ParkingLot)和一个停车位类(ParkingSpot)。在停车场类中,初始化方法__init__()中接收一个参数num_spots表示停车位数量,会生成num_spots个停车位对象存储在spots列表中。类方法park_vehicle()和release_spot()可以分别用于停车和释放停车位,根据停车位状态(是否被占用)进行相应操作,并输出相应提示信息。类方法display_spots()用于展示当前停车位的状态信息。停车位类中,初始化方法__init__()中接收一个参数spot_id表示停车位编号,同样会根据编号生成一个状态(status)字符串,如果没有传入状态参数,则默认为'Available'。类方法str()可以返回当前停车位的状态信息。
阅读全文