使用子类

时间:2017-09-20 03:28:58

标签: python python-3.x class queue subclass

作为一个相对较新的python程序员,我最近试图通过使用类和子类来模拟入队和出队。目前,我的代码读取加上尝试执行读取:

class queue:
    class node:
        def __init__(self, value, nextNode):
            self.value = value
            self.nextNode = nextNode

    def __init__(self):
        self.top = None
        self.last = None
        self.size = 0

    def __len__(self):
        return self.size

    def enqueue(self, value):
        #This creates an extra node with "value" and inserts at the top
        newNode=queue.node(value,None)
        if self.size ==0:
            self.top=newNode
            self.last=self.top
            self.size+=1
        else:
            self.last.nextNode=newNode
            self.last=newNode
            self.size+=1      

    def dequeue(self):
        #This returns self.top.value and at the same time deletes the top 
         node.
        if self.size ==0:
            return "error: dequeue from an empty queue"
        elif self.size == 1:
            val=self.top.value
            nxt=self.top.nextNode
            self.top=None
            self.last=None
        else:
            val=self.top.value
            nxt=self.top.nextNode
            self.top=nxt
        return val

q = queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
x=q.dequeue()
output = []
while len(q)>0:
    x = q.dequeue()
    output.append(x)
print(output)
#This should show [2, 3, 4]

根据我的理解,我的主要问题是返回我目前收到的值:

AttributeError:' NoneType'对象没有属性'值'

当我试图跑步时。如果有人能够澄清问题所在,那将非常感激。

1 个答案:

答案 0 :(得分:0)

当你出列东西时,你需要减少self.size。从程序运行到pdb总是4。

def dequeue(self):
    if self.size ==0:
        return "error: dequeue from an empty queue"
    elif self.size == 1:
        val=self.top.value
        nxt=self.top.nextNode
        self.top=None
        self.last=None
        self.size -= 1
    else:
        val=self.top.value
        next=self.top.nextNode
        self.top=next
        self.size
        self.size -= 1
    return val