如何在python 3.6中创建一个简单的类Queue?

时间:2018-06-15 23:04:51

标签: python queue python-3.6

我是初学者。这是我的代码:

class Queue: 
    def __init__(self):
        self.queue = []
    def dequeue(self):
        self.queue.pop(O) 
    def enqueue(self,element):
        self.queue.append(element)
q=Queue()
q.enqueue('dog')
print(q)

但是!我明白这一点:

<__main__.Queue object at 0x00A3FC10>

这是什么?如何创建这个类?

1 个答案:

答案 0 :(得分:2)

这是您的类实例的默认显示表示。默认设置是在内存中显示类名及其实例的地址。您可以覆盖__repr____str__来自定义表示形式:

class Queue: 

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

    def dequeue(self):
        return self.queue.pop(0) # probably want to return what you dequeue.

    def enqueue(self,element):
        self.queue.append(element)

    # Customize debug representation...you want to know it is a Queue and what is in it.
    def __repr__(self):
        return f'Queue({self.queue})'

    # Customize print representation...may just want to see the list.
    def __str__(self):
        return f'{self.queue}'

q=Queue()
q.enqueue('dog')
q.enqueue('cat')
print(repr(q))
print(q)
print(f'popped {q.dequeue()}')
print(q)

输出:

Queue(['dog', 'cat'])
['dog', 'cat']
popped dog
['cat']