0

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]
1
  • 1
    You might want to look at NetworkX Commented May 22, 2014 at 20:17

1 Answer 1

2

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 = []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.