【发布时间】:2019-10-06 07:55:15
【问题描述】:
我正在构建一个文件系统分析器,并且我有一个名为 HashableHeap 的类,它覆盖了 __hash__ 函数以使用文件扩展名进行散列。我有一本将扩展映射到堆的字典。例如 .jpg 堆需要保存 jpg 对象,当我为 .jpg 散列时,它应该给我相应的堆。
问题是:当我遇到不在字典键中的扩展时,我会创建一个新堆并添加它。当代码尝试创建和添加一个新堆时,它也会修改第一个堆。例如:假设它首先将 .json 堆添加到 dict。然后它遇到一个 .sql 文件并创建一个同名的新堆。当它添加新堆时,.sql 文件也会添加到 .json 堆中。所有堆都是相同的内容,但键不同。
我认为这是关于引用,我试图删除新的堆对象但它没有改变。也许我需要像行为一样按值传递,但我是 Python 的初学者。
def add_to_dictionary(directory, abs_path):
# Creates a file obj from path and adds to heap
for file in directory:
try:
f = File(os.path.join(abs_path, file))
if f.extension in extension_dictionary.keys(): # check if the corresponding heap exists for extension x
hashable_heap = extension_dictionary[f.extension]
hashable_heap.total_size += f.size
heapq.heappush(hashable_heap.heap, f)
elif f.extension != '': # if the heap does not exist, create and add with current file
new_heap = HashableHeap(f.extension)
new_heap.total_size = f.size
extension_dictionary[f.extension] = new_heap
heapq.heappush(extension_dictionary[f.extension].heap, f)
except FileNotFoundError:
print(os.path.join(abs_path, file))
print('No permission')
这是HashableHeap 的代码,因为它是被请求的:
class HashableHeap:
# wrapper class for heaps, required for the extension based hashing
heap = []
extension = ''
total_size = 0
def __init__(self, extension):
self.extension = extension
def __hash__(self):
hash(self.extension)
def __lt__(self, other): # Comparator of the heaps by their sizes
return self.total_size > other.total_size
PyCharm 调试截图:
【问题讨论】:
-
你应该显示 HashableHeap 的代码。
-
添加了 HashableHeap
标签: python python-3.x operating-system parameter-passing pass-by-reference