0

The code below return this:

Person A have friends ['B', 'A']
Person B have friends ['B', 'A']

But it is intended to return:

Person A have friends ['B']
Person B have friends ['A']

"A" must reference "B" and vice-versa. But "A" is referencing "B" and "A", why?

CODE:

class person:
    name = ""
    friends = set()

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

    def add(self, new):
        self.friends |= {new}
        new.friends |= {self}
#---------------------------------------------------------------------------
pa = person("A")
pb = person("B")

pa.add(pb)

print( "Person", pa.name, "have friends", [f.name for f in pa.friends] )
print( "Person", pb.name, "have friends", [f.name for f in pb.friends] )
  • I would suggest reading through [Python's great documentation on classes](https://docs.python.org/2/tutorial/classes.html). – squiguy Oct 18 '16 at 17:36

2 Answers2

3
class person:
    name = ""
    friends = set()

With this construct, the friends set is an attribute on the classobject person. This means the same set is shared between each instance. In your add method, self.friends and new.friends is literally the same object.

To change the friends set to an instance variable:

class Person:
    def __init__(self, name):
        self.name = name
        self.friends = set()

    def add(self, new):
        self.friends |= {new}
        new.friends |= {self}
wim
  • 338,267
  • 99
  • 616
  • 750
1

You are declaring friends as a class variable. You can declare it in the scope of the instance by setting it in __init__:

class person:
    name = ""
    def __init__(self, name):
        self.friends = set()
        self.name = name

    def add(self, new):
        self.friends |= {new}
        new.friends |= {self}
brianpck
  • 8,084
  • 1
  • 22
  • 33