user3527671
user3527671

Reputation:

Elements in array duplicated

I'm new to Python3 and I have problems with duplicated elements in arrays. Let's say I have this example:

class A:
  arr1 = []

  def __init__(self):
    pass

  def add(self, b):
    self.arr1.append(b)

class B:
  arr2 = []

  def __init__(self):
    pass

  def add(self, val):
    self.arr2.append(val)

So A contains array of objects of B, and B contains array of values. If I add values like this:

a = A()
b1 = B()
b2 = B()
a.add(b1)
a.add(b2)
a.arr1[0].add(5)
a.arr1[0].add(6)
a.arr1[1].add(3)

And then print output like this:

for e in a.arr1:
  for ee in e.arr2:
    print(ee)

I get output: 5 6 3 5 6 3, why it isn't just 5 6 3 ? I can't figure out what I'm missing. Thanks for help. Btw. I simplified the code just for this specific problem (duplicated values).

Upvotes: 0

Views: 62

Answers (1)

Hai Vu
Hai Vu

Reputation: 40733

When you declare class B like this:

class B:
  arr2 = []
  ...

then arr2 is a class-level attribute, that means it is shared among the objects. What you want to do is:

class B:
  def __init__(self):
    self.arr2 = []

This way, arr2 is different for each object. The same goes for class A and arr1.

Upvotes: 2

Related Questions