[英]Pointer error in Directed Graph in Python
I'm trying to implement a Directed graph in python by creating a class Vertex
.我正在尝试通过创建 class
Vertex
在 python 中实现有向图。 A vertex has the name
and the adjacent
as a list containing another instance of class Vertex
.顶点具有
name
和adjacent
的列表,其中包含instance of class Vertex
。 below is the code.下面是代码。
The problem is that when I assign node b
as the adjacent
node from node a
.问题是当我将
node b
分配为节点node a
的adjacent
节点时。 the pointer of node b
is assigned to both adjacent of a
and b
which is not my intention. node b
的指针被分配给a
和b
的相邻节点,这不是我的意图。
I also have the picture debug mode below the code showing that the pointer of node b is also assigned to itself.我在代码下方还有图片调试模式,显示节点 b 的指针也分配给了它自己。
how to fix it?如何解决?
class Vertex: def __init__(self, name, adjacent=[]): self.name = name self.adjacent = adjacent def add_adjacent(self, vertex): self.adjacent.append(vertex) class Graph: # directed graph def __init__(self, edge_list): vertices = {} for o, d in edge_list: # print(o, d) if o not in vertices: v = Vertex(o) vertices[o] = v else: v = vertices[o] if d not in vertices: u = Vertex(d) vertices[d] = u else: u = vertices[d] if u not in v.adjacent: print(v.name, ' adds ', u.name) v.add_adjacent(u) self.vertices = vertices def get_vertex_names(self): return list(self.vertices.keys()) def get_adjacent(self, vertex): return self.vertices[vertex].adjacent # test Vertex edges = [ ['a', 'b'], ['a', 'c'], ['a', 'd'], ['b', 'c'], ['c', 'b'], ] g = Graph(edges) # g.vertices
You wrote this:你写了这个:
def __init__(self, name, adjacent=[]):
There is a subtle "gotcha", summarized by a simple rule,有一个微妙的“陷阱”,用一个简单的规则概括,
Avoid using mutable container as a default arg.避免使用可变容器作为默认参数。
You want this:你要这个:
def __init__(self, name, adjacent=None): self.name = name self.adjacent = adjacent or []
In the original, there is a single list
for all vertices (since caller always lets it default).在原始版本中,所有顶点都有一个
list
(因为调用者总是让它默认)。 That list was created at def
time.该列表是在
def
时间创建的。 In contrast, the or []
clause constructs a new list at execution time each time through, rather than once during definition.相反,
or []
子句在每次执行时构造一个新列表,而不是在定义期间构造一次。
https://dollardhingra.com/blog/python-mutable-default-arguments/ https://dollardhingra.com/blog/python-mutable-default-arguments/
https://towardsdatascience.com/python-pitfall-mutable-default-arguments-9385e8265422 https://towardsdatascience.com/python-pitfall-mutable-default-arguments-9385e8265422
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.