python学习之打印机

Posted 今夜月色很美

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之打印机相关的知识,希望对你有一定的参考价值。

1、创建打印任务类

import random

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

2、创建打印机类

from queue import Queue


class Printer:
    def __init__(self, speed):
        self.speed = speed
        self.currentTask = None
        self.timeRemaining = 0
        self.queue = Queue()
        self.waitTimes = []

    def isBusy(self):
        return self.currentTask != None

    def tick(self, currentTime):
        if self.currentTask != None:
            self.timeRemaining = self.timeRemaining - 1
            if self.timeRemaining <= 0:
                self.currentTask = None
        elif self.queue.size() > 0:
            self.currentTask = self.queue.dequeue()
            self.waitTimes.append(self.currentTask.waitTime(currentTime))
            self.timeRemaining = self.currentTask.getPages() * 60 / self.speed

    def addTask(self, task):
        self.queue.enqueue(task)

    def getWaitTimes(self):
        return self.waitTimes

3、测试类

import random
from task import Task
from printer import Printer


def newPrinterTask():
    num = random.randrange(1, 181)
    if num == 180:
        return True
    else:
        return False


def simulation(testSeconds, speed):
    test_printer = Printer(speed)
    for i in range(testSeconds):
        if newPrinterTask():
            newTask = Task(i)
            test_printer.addTask(newTask)
            execTime = newTask.getPages() * 60 / speed
            print("%s====new task有%s页 执行需要%s"%(i, newTask.getPages(),execTime))
        test_printer.tick(i)

    print(test_printer.getWaitTimes())


simulation(3600, 5)

以上是关于python学习之打印机的主要内容,如果未能解决你的问题,请参考以下文章

Python面向对象学习之八,装饰器

Python学习之day2

python学习之调试:

python学习之循环

python 学习之 PythonBasic2

Python学习之函数篇