这个案例作者把大部分代码都已经给出了,但是ERModel类没有给出,此外,Condition和Patient这两个类在原书的基础上还需要增加一些代码,具体如下。
Patient类中原书只是重载了 >= 运算符,虽然在LinkedPriorityQueue类中这是主要使用的运算符,但还用到了 == 这个元素符,所以还要对这个元素符进行重载;为了以防万一,这里对 < > <= 这几个元素符也进行了重载。具体代码如下:
class Patient(object):
"""Represents a patient with a name and a condition."""
def __init__(self, name, condition):
self._name = name
self._condition = condition
def __eq__(self, other):
return self._condition == other._condition
def __lt__(self, other):
return self._condition < other._condition
def __le__(self, other):
return self._condition <= other._condition
def __gt__(self, other):
return self._condition > other._condition
def __ge__(self, other):
return self._condition >= other._condition
def __str__(self):
"""Returns the string rep of a patient."""
return self._name + " / " + str(self._condition)
因为在Patient类中是对Condition类的实例进行比较,所以相应的要在Condition中对这几个运算符进行重载,代码时类似的,只不过比较的对象不同。具体代码如下:
class Condition(object):
"""Represents a condition."""
def __init__(self, rank):
self._rank = rank
def __eq__(self, other):
return self._rank == other._rank
def __lt__(self, other):
return self._rank < other._rank
def __le__(self, other):
return self._rank <= other._rank
def __gt__(self, other):
return self._rank > other._rank
def __ge__(self, other):
return self._rank >= other._rank
def __str__(self):
"""Returns the string rep of a condition."""
if self._rank == 1: return "critical"
elif self._rank == 2: return "serious"
else: return "fair"
最后是写ERModel类,从ERView类中可知这个类需要具备的方法包括treatNext(), schedule()以及isEmpty() ,每个函数的实现也比较简单,具体代码如下:
from linkedpriorityqueue import LinkedPriorityQueue
class ERModel(object):
def __init__(self):
self._queue = LinkedPriorityQueue() # 初始化一个优先队列
def treatNext(self):
return str(self._queue.pop()) # 弹出优先队列中位于队头的对象,这是个Patient对象
def schedule(self, p):
self._queue.add(p) # 将先输入的Patient类的实例p插入优先队列中
def isEmpty(self):
return len(self._queue) == 0
以上在结合 erapp.py、 linkedpriority.py、linkedqueue.py 以及 abstractcollection.py即可正确运行。