Reputation: 1320
I plan on using python to analyze various walk along graphs. To do so I created a vertex class, two of which can be linked to form an edge. The connections a vertex has are stored in its connections list. The class also has other functions with return connected vertices, however for brevity they have been omitted. For some reason the link function causes vertices to be linked with other not-specified vertices (in this example with itself). What causes this?
class vertex:
connections=[]
def __init__(self,na):
self.name=na
def __repr__(self):
return self.name
def display(self):
return self.name+' is linked with '+str(self.connections)
def link(v1,v2):
print('linking',v1,v2)
v1.connections.append(v2)
v2.connections.append(v1)
a=vertex('a')
b=vertex('b')
link(a,b)
print(a.display())
Output:
linking a b
a is linked with [b, a]
Expected Output:
linking a b
a is linked with [b]
Upvotes: 0
Views: 99
Reputation: 599778
Because connections is a class variable, so is shared among all instances. Define it in __init__
instead.
class vertex:
def __init__(self, na):
self.name = na
self.connections = []
Upvotes: 2