我正在修读数据结构课程,而我不了解课程如何调用另一个课程中的方法。
以下代码有两个类:Printer
和Task
请注意,类Printer
有一个名为startNext
的方法,其变量self.timeRemaining
会被赋予newTask.getPages() * 60/self.pagerate
的结果。
newTaks
如何从Task类引用getPages()
方法?
将此对象传递给Printer类的代码从不引用Task类
代码有效,因为这是课程提供的内容,但我无法理解如何访问该方法
代码:
from pythonds.basic.queue import Queue
import random
class Printer:
def __init__(self, ppm):
self.pagerate = ppm
self.currentTask = None
self.timeRemaining = 0
def tick(self):
if self.currentTask != None:
self.timeRemaining = self.timeRemaining - 1
if self.timeRemaining <= 0:
self.currentTask = None
def busy(self):
if self.currentTask != None:
return True
else:
return False
def startNext(self, newTask):
self.currentTask = newTask
self.timeRemaining = newTask.getPages() * 60/self.pagerate
class Task:
def __init__(self, time):
self.timeStamp = time
self.pages = random.randrange(1, 21)
def getStamp(self):
return self.timeStamp
def getPages(self):
return self.pages
def waitTime(self, currentTime):
return currentTime - self.timeStamp
def simulation(numSeconds, pagesPerMinute):
labPrinter = Printer(pagesPerMinute)
printQueue = Queue()
waitingTimes = []
for currentSecond in range(numSeconds):
if newPrintTask():
task = Task(currentSecond)
printQueue.enqueue(task)
if (not labPrinter.busy()) and (not printQueue.isEmpty()):
nextTask = printQueue.dequeue()
waitingTimes.append(nextTask.waitTime(currentSecond))
labPrinter.startNext(nextTask)
labPrinter.tick()
averageWait = sum(waitingTimes)/len(waitingTimes)
print "Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printQueue.size())
def newPrintTask():
num = random.randrange(1, 181)
if num == 180:
return True
else:
return False
for i in range(10):
simulation(3600, 5)
答案 0 :(得分:1)
如果我清楚地理解你的问题,那是因为你要将任务对象添加到队列列表中。然后,当您获得对象(列表项)时,您将再次获得任务对象:
#creating Task object and adding to Queque list
task = Task(currentSecond)
printQueue.enqueue(task)
class Queue:
def __init__(self):
#list of task objects
self.items = []
def enqueue(self, item):
#you are inserting Task object item to list
self.items.insert(0,item)
def dequeue(self):
#returns task object
return self.items.pop()
那么你可以从Printer类调用startNext()方法,因为dequeue()方法正在返回Task对象。
由于startNext()中的对象是Task的类型,您可以在该对象上调用getPages()方法。
答案是否足够?