0

I'm trying to add objects to a list but when I print elements of that list, I get the attributes of the last object.

import random


class Unit:
    arr = []

    def __init__(self):
        self.arr.clear()
        for i in range(2):
            self.arr.append(random.randint(1, 100))
            print("arr in Unit ", self.arr)

class SetOfUnits:

    lst = []

    def __init__(self):
        self.lst.clear()
        for i in range(3):
            self.lst.append(Unit())
            print("arr in SetOfUnits ", self.lst[i].arr)


p = SetOfUnits()

for i in range(3):
    print(p.lst[i].arr)

I got this:

arr in Unit  [17, 16]
arr in SetOfUnits  [17, 16]
arr in Unit  [98, 20]
arr in SetOfUnits  [98, 20]
arr in Unit  [16, 39]
arr in SetOfUnits  [16, 39]
[16, 39]
[16, 39]
[16, 39]

The problem is with the last 3 lines. It looks like that objects p.lst[0], p.lst[1], p.lst[2] refer to the same object, not different ones. I would like to get:

[17, 16]
[98, 20]
[16, 39]

Could you help me to find out what am I doing wrong?

MFrost
  • 1

2 Answers2

2

Define your lists inside the __init__ function.

class Unit:

    def __init__(self):
        self.arr = []
        self.arr.clear()
        for i in range(2):
            self.arr.append(random.randint(1, 100))
            print("arr in Unit ", self.arr)

class SetOfUnits:

    def __init__(self):
        self.lst = []
        self.lst.clear()
        for i in range(3):
            self.lst.append(Unit())
            print("arr in SetOfUnits ", self.lst[i].arr)

The way you are doing it, you define your variables class-wise, you need it to be instance-wise.

See: class variable vs instance variable --Python

Rockybilly
  • 2,938
  • 1
  • 13
  • 38
0

lst and arr are class attributes, not instance attributes.

double-beep
  • 5,031
  • 17
  • 33
  • 41
wangtianye
  • 306
  • 1
  • 5