写一个Building类,并实现电梯功能
Building有不同的入口,我们假设不同入口进入的单元楼是不同的,但都属于同一单元
实现乘电梯上楼与离开楼的功能,并在数据错误时进行报错
代码如下:
class BuildingError(Exception):
pass
class Building:
number_created = 0
def __init__(self, height, entries):
Building.number_created += 1
self.height = height
self.entries = entries
self.the_entries = entries.split()
self.lifts = {entry: 0 for entry in self.the_entries}
self.occupancies = {(entry, floor): 0
for entry in self.the_entries
for floor in range(0, self.height)
}
def __repr__(self):
return f"Building({self.height}, '{self.entries}')"
def __str__(self):
return 'Building with ' +\
(self.height == 0 and '1 floor ' or\
f'{self.height + 1} floors '\
) + 'accessible from entries: ' + ', '.join(self.the_entries)
def go_to_floor_from_entry(self, floor, entry, nb_of_people):
if not 0 <= floor <= self.height\
or entry not in self.the_entries\
or nb_of_people <= 0:
raise BuildingError("That makes no sense!")
self.occupancies[entry, floor] += nb_of_people
if floor:
if self.lifts[entry]:
print('Wait, lift has to go down', self.lifts[entry],
self.lifts[entry] > 1 and 'floors...'\
or 'floor...'
)
self.lifts[entry] = floor
def leave_floor_from_entry(self, floor, entry, nb_of_people):
if not 0 <= floor <= self.height\
or entry not in self.the_entries\
or nb_of_people <= 0:
raise BuildingError("That makes no sense!")
if self.occupancies[entry, floor] < nb_of_people:
raise BuildingError("There aren't that many people on that floor!")
self.occupancies[entry, floor] -= nb_of_people
if floor:
if self.lifts[entry] > floor:
difference = self.lifts[entry] - floor
print('Wait, lift has to go down', difference,
difference != 1 and 'floors...' or 'floor...'
)
if self.lifts[entry] < floor:
difference = floor - self.lifts[entry]
print('Wait, lift has to go up', difference,
difference != 1 and 'floors...' or 'floor...'
)
self.lifts[entry] = 0
def compare_occupancies(building_1, building_2):
occupancy_1 = sum(building_1.occupancies.values())
occupancy_2 = sum(building_2.occupancies.values())
if occupancy_1 == occupancy_2:
print('There is the same number of occupants in both buildings.')
elif occupancy_1 > occupancy_2:
print('There are more occupants in the first building.')
else:
print('There are more occupants in the second building.')