Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.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-can';t定义一组用户定义的对象_Python_Set - Fatal编程技术网

Python-can';t定义一组用户定义的对象

Python-can';t定义一组用户定义的对象,python,set,Python,Set,我得到以下错误 all_rots = set([rot1, rot2]) TypeError: an integer is required 我的代码很简单 rot1 = SimpleClass(mapping={1:1, 2:2}) rot2 = SimpleClass(mapping={2:2, 1:1}) all_rots = set([rot1, rot2]) (这是单元测试) SimpleClass类是 class SimpleClass(object): def

我得到以下错误

    all_rots = set([rot1, rot2])
TypeError: an integer is required
我的代码很简单

rot1 = SimpleClass(mapping={1:1, 2:2})
rot2 = SimpleClass(mapping={2:2, 1:1})
all_rots = set([rot1, rot2])
(这是单元测试)

SimpleClass类是

class SimpleClass(object):
    def __init__(self, mapping):
        self._mapping = mapping


    @property
    def mapping(self):
        return self._mapping


    def __getitem__(self, key):
        return self.mapping[key]

    def __hash__(self):
        return sorted(list(self.mapping.iteritems()))

    def __eq__(self, other):
        if type(other) is type(self):
            return self.__dict__ == other.__dict__
        return False

有人知道我为什么不能构造一组对象吗?

\uuuuu散列\uuuuu
应该返回一个整数而不是列表

您可以从排序列表(例如元组)创建不可变/可散列类型,并返回该类型的散列:

def __hash__(self):
    return hash(tuple(sorted(self.mapping.items())))

rot1=SimpleClass(映射={1:1,2:2})
rot2=SimpleClass(映射={2:2,1:1})
所有旋转=设置([rot1,rot2])
打印所有文件
#集合([])

\uuuuuuuuuuuuuuuuuuuuuu
应返回整数而不是列表

您可以从排序列表(例如元组)创建不可变/可散列类型,并返回该类型的散列:

def __hash__(self):
    return hash(tuple(sorted(self.mapping.items())))

rot1=SimpleClass(映射={1:1,2:2})
rot2=SimpleClass(映射={2:2,1:1})
所有旋转=设置([rot1,rot2])
打印所有文件
#集合([])

\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>应返回一个整数而不是一个列表。另外
我明白了。有什么办法可以修复它吗?我基本上是在尝试对字典进行哈希处理,我的类是字典的包装器。这是如何正确完成的?@juanpa.arrivillaga仅在python 2中使用。但是
\uuuuuuhash\uuuuuu
无论如何应该返回一个int。那么,修复我的方法的最佳方法是什么呢?例如,我如何获得一个可哈希的dict?
\uuuuhash\uucode>should返回一个整数而不是一个列表。另外,
list(self.mapping.iteritems()
相当于
self.mapping.items())
我明白了。有什么办法可以修复它吗?我基本上是在尝试对字典进行哈希处理,我的类是字典的包装器。这是如何正确完成的?@juanpa.arrivillaga(仅适用于python 2)。但是
\uuuuuhash\uuuu
无论如何都应该返回一个int。那么,修复我的方法的最佳方法是什么呢?例如,我如何获得一个可哈希的dict呢?比我快几秒钟:)
sorted
可以更好地处理
items()
(不需要为python 2重建列表,也可以在python 3中工作)比我快了几秒钟:)
sorted
可以更好地处理
items()
(不需要为python 2重建列表,也可以在python 3中工作)