class FixedSizeHeap: def __init__(self, max_size): self.max_size = max_size self.heap = [] def push(self, item): if len(self.heap) < self.max_size: heapq.heappush(self.heap, item) else: min_item = heapq.heappop(self.heap) if item > min_item: heapq.heappush(self.heap, item) else: heapq.heappush(self.heap, min_item) def pop(self): return heapq.heappop(self.heap) def __len__(self): return len(self.heap)对于这样的类怎么打印类中的元素
时间: 2024-02-10 09:08:43 浏览: 68
mysql tmp_table_size和max_heap_table_size大小配置
要打印类中的元素,可以通过实现`__str__`方法来实现。`__str__`方法应该返回一个字符串,该字符串包含对象的信息。例如,以下代码演示了如何在类中实现`__str__`方法以打印堆的元素:
```
import heapq
class FixedSizeHeap:
def __init__(self, max_size):
self.max_size = max_size
self.heap = []
def push(self, item):
if len(self.heap) < self.max_size:
heapq.heappush(self.heap, item)
else:
min_item = heapq.heappop(self.heap)
if item > min_item:
heapq.heappush(self.heap, item)
else:
heapq.heappush(self.heap, min_item)
def pop(self):
return heapq.heappop(self.heap)
def __len__(self):
return len(self.heap)
def __str__(self):
return str(self.heap)
new_heap = FixedSizeHeap(5)
new_heap.push(1)
new_heap.push(2)
new_heap.push(3)
new_heap.push(4)
new_heap.push(5)
print(new_heap) # 输出 [1, 2, 3, 4, 5]
```
在这个例子中,我们定义了`__str__`方法来返回堆的元素。我们将`self.heap`转换为字符串并返回。现在,当我们打印`new_heap`时,它将打印堆中的元素。
阅读全文