Python中使用队列的打印机实词模拟

2024-05-15 11:58:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读《用Python算法和数据结构解决问题》一书

在“队列”一章中,使用printer类进行了打印机模拟。你知道吗

以下是打印机类的定义:

class Printer():
def __init__(self, ppm):
    self.pagerate = ppm
    self.currentTask = None
    self.timeRemaining = 0

我的问题是,实例变量如何在参数中不存在,但仍然被定义(例如currentTask和timeRemaining)?你知道吗

这是Python中的一种实践吗?还有其他更好的方法吗?你知道吗


Tags: self算法数据结构定义队列initdef打印机
2条回答

来自文档https://docs.python.org/3/tutorial/classes.html#class-objects

The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:

def __init__(self):
    self.data = []

Instance variables vs. class variables in Python

不需要为所有参数传递值。通过编写self.variable_name,我们自动创建实例变量。它们不需要用传递的值初始化。您可以用None值初始化它们。你知道吗

相关问题 更多 >