gpt4 book ai didi

python - 属性错误 : Edge instance has no attribute 'vto'

转载 作者:太空宇宙 更新时间:2023-11-03 11:10:41 25 4
gpt4 key购买 nike

我正在尝试 pickle 包含两个其他实例列表的类实例。两个列表中的实例具有相互引用实例的属性。这是类。

class Graph:
def __init__(self):
self.vertices = {}
self.edges = set()
def __repr__(self):
return "\n".join(map(str, sorted(self.vertices, key=lambda v:v.id)))

class Edge:
def __init__(self, vfrom, vto):
self.vfrom = vfrom
self.vto = vto
def __hash__(self):
return hash(tuple(map(hash, (self.vto, self.vfrom))))
def __repr__(self):
return str(self.vto.id)

class Vertax:
def __init__(self, id):
self.id = id
self.incoming = set()
self.outgoing = set()
def __repr__(self):
return "Vertax %d -> %s"%(self.id, ", ".join(map(str, self.outgoing)))
def __hash__(self):
return hash(self.id)

当我尝试 pickle 一个简单的图形时,unpickling 给出了一个错误。

>>> v0 = Vertax(0)
>>> v1 = Vertax(1)
>>> e0to1 = Edge(v0, v1)
>>> v0.outgoing.add(e0to1)
>>> v1.incoming.add(e0to1)
>>> g = Graph()
>>> g.vertices[v0] = v0
>>> g.vertices[v1] = v1
>>> g.edges.add(e0to1)
>>> print g
Vertax 0 -> 1
Vertax 1 ->
>>>
>>> import pickle
>>> p = pickle.dumps(g)
>>> pickle.loads(p)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/pickle.py", line 1374, in loads
return Unpickler(file).load()
File "/usr/lib/python2.6/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.6/pickle.py", line 1133, in load_reduce
value = func(*args)
File "<stdin>", line 6, in __hash__
AttributeError: Edge instance has no attribute 'vto'

我发现如果注释掉 Edge 类的 __hash__ 函数,错误就会消失。我需要你的帮助来理解为什么会这样。

最佳答案

这个 Python 问题可能是原因:http://bugs.python.org/issue1761028

“pickle - 无法使用自定义 __hash__ unpickle 循环依赖”

关于python - 属性错误 : Edge instance has no attribute 'vto' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4425472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com