我是初学者。这是我的代码:
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>
这是什么?如何创建这个类?
答案 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']