设计一个建筑物基类Building,由它派生出宿舍类Hostel和教学楼类Classroom,前者包括楼名、总层数、住户数、总住人数和总面积,后者包括楼名、总层数、教室数、灭火器数和总面积。
时间: 2024-01-31 18:04:14 浏览: 136
下面是基类Building的实现:
```python
class Building:
def __init__(self, name, floors, area):
self.name = name
self.floors = floors
self.area = area
```
宿舍类Hostel和教学楼类Classroom则分别继承于基类Building,实现各自的特定属性和方法:
```python
class Hostel(Building):
def __init__(self, name, floors, area, rooms, beds_per_room):
super().__init__(name, floors, area)
self.rooms = rooms
self.beds_per_room = beds_per_room
self.occupants = 0
def total_beds(self):
return self.rooms * self.beds_per_room
def add_occupants(self, occupants):
self.occupants += occupants
def total_occupants(self):
return self.occupants
class Classroom(Building):
def __init__(self, name, floors, area, classrooms, fire_extinguishers):
super().__init__(name, floors, area)
self.classrooms = classrooms
self.fire_extinguishers = fire_extinguishers
def total_fire_extinguishers(self):
return self.classrooms * self.fire_extinguishers
```
使用示例:
```python
h1 = Hostel("Building A", 5, 1000, 50, 4)
h1.add_occupants(150)
print(h1.total_beds()) # 200
print(h1.total_occupants()) # 150
c1 = Classroom("Building B", 3, 500, 10, 2)
print(c1.total_fire_extinguishers()) # 20
```
阅读全文