2

I am trying to create a method that allows each instance of the class to be "neighbors" of each other. If Entity A adds B as a neighbor, then B is in A's neighbor_list. However, as the output below shows, B is automatically added to B's neighbor list and that's not the desired behavior - B's neighbor list should be empty. Any thoughts?

Output:

 a's neighbor list element: b
 b's neighbor list element: b

Code:

 class Entities:
     neighbor_list = []
     name = ''

     def __init__(self,name):
         self.name = name

     def add (self, neighbor):
         self.neighbor_list.append(neighbor)  

 a = Entities ('a')
 b = Entities ('b')
 a.add(b)
 print "a's neighbor list element: %s" % a.neighbor_list[0].name
 print "b's neighbor list element: %s" % b.neighbor_list[0].name
2
  • 2
    Why does it surprise you that mutating a class attribute means that all instances can see the mutation? Commented Jan 11, 2014 at 0:51
  • 1
    @IgnacioVazquez-Abrams: Well, presumably what surprises him is that neighbor_list is a class member rather than an instance member, because he assumed that Python did members exactly like, say, Java. Commented Jan 11, 2014 at 0:52

1 Answer 1

6

Make neighbor_list an instance, not class, attribute:

class Entities(object):
    # not here
    def __init__(self, name):
        self.name = name
        self.neighbor_list = [] # here

Class attributes, defined outside the instance methods, are shared by all instances of the class.

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.