Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 包装我的哈希表类_Python_Wrapper_Python Decorators - Fatal编程技术网

Python 包装我的哈希表类

Python 包装我的哈希表类,python,wrapper,python-decorators,Python,Wrapper,Python Decorators,我需要能够包装一个哈希表类。在阅读了包装器之后,我很确定这是包装器的一个不好的用法,然而这是在我的作业中。(我有不同的数据结构,需要在程序中轻松交换) 我有以下代码: from HashTable import HashTable class HashTableWrapper(HashTable): def __init__(self, probe, size): super().__init__(probe, size) def tableInsert(s

我需要能够包装一个哈希表类。在阅读了包装器之后,我很确定这是包装器的一个不好的用法,然而这是在我的作业中。(我有不同的数据结构,需要在程序中轻松交换)

我有以下代码:

from HashTable import HashTable

class HashTableWrapper(HashTable):

    def __init__(self, probe, size):
        super().__init__(probe, size)

    def tableInsert(self, searchKey, newItem):
        return self.HashTable.tableInsert(searchKey, newItem)

    def tableRetrieve(self, searchKey):
        return self.HashTable.tableRetrieve(searchKey)

    def tableDelete(self, searchKey):
        return self.HashTable.tableDelete(searchKey)
当我使用:

x = HashTableWrapper("linearProbe", 100)
但是,如果我使用以下方法,一切都很好:

x.tableInsert(4, 6)
我得到以下错误:AttributeError:'HashTableWrapper'对象没有属性'HashTable' 我认为返回部分有问题,因为python还突出显示了所有哈希表部分。 我们将非常感谢您的帮助

编辑:我得到了以下示例:

class BSTTableWrapper:
   def tableInsert(item):
       return self.bst.searchtreeInsert(item)

self.HashTable
从未初始化,因此调用
self.HashTable.
将无法工作。如果HashTable对象具有方法
tableInsert
,那么您所要做的就是

def tableInsert(self, searchKey, newItem):
    return self.tableInsert(searchKey, newItem)

def tableRetrieve(self, searchKey):
    return self.tableRetrieve(searchKey)

def tableDelete(self, searchKey):
    return self.tableDelete(searchKey)

因为函数/方法是从哈希表继承的。

是的,它没有
HashTable
属性-您还没有组合来构建包装,而是继承了。它应该是例如self.tableInsert(searchKey,newItem)。但问题是:包装的意义是什么?当我现在尝试插入一个项目时,我得到:[上一行重复了995次]递归错误:超过了最大递归深度。我想重点是我的hashtable、binarysearchtree、2-3-4tree等所有类似的函数都会有相同的名称,因为包装器。因此,如果我想切换到不同的结构,我可以只导入另一个包装器,但所有函数名将保持不变。或者我错了?对不起,是的,如果你只在
self
上调用它,你会得到一个永无止境的递归。您需要
super().tableInsert(…)
,才能调用该方法的父类版本,就像您在
\uuuuu init\uuuu
中所做的那样。如果包装器接口与父接口完全相同,那就没有什么好处了。谢谢你的帮助,它现在似乎可以工作了。由于前面提到的原因,我现在不得不使用它。然而,你会说这通常是包装器的一个坏用法吗?毫无意义,而不是坏的。如果您的想法是使用同一接口有多个实现,那么使用它们都继承的抽象基类处理这些实现会更明智。