0
class Numbers:
    data = []
    def read_from_row(self, row):
        row_list = list(row)
        for i in row_list:
            self.data.append(i)


list1 = ["15","16"]
list2 = ["17","18"]

instance = Numbers()
instance.read_from_row(list1)
print(instance.data)

instance = Numbers()
instance.read_from_row(list2)
print(instance.data)

Here is the piece of code. So in the beginning instance is the instance of the class Numbers and after reading the first list print(instance.data) naturally prints ['15', '16']. But then I create new instance of class Numbers again still in the same variable instance, but after reading from the second list it still contains data from the first list for some reason. Outputting ['15', '16', '17', '18'].

I'm sorry, I'm a beginner at python and after coding C/C++ for so long I can't understand why does this happen or what's expected behavior. I'm using Python 2.7.

Thanks in advance.

Filip Malczak
  • 3,124
  • 24
  • 44
JukesOnYou
  • 263
  • 2
  • 10

3 Answers3

2

Data is not an instance member but a class member. All instances of numbers class "share" the same Data list.

See also here: Python: Difference between class and instance attributes

In order to do what you expect:

class Numbers:
    def __init__(self):
        self.data = []
    def readFromRow(self, row):
        self.data.extend(row)
Community
  • 1
  • 1
gosom
  • 1,299
  • 3
  • 16
  • 35
2

Instance variables are created in __init__(..):

class Numbers(object):               # in Python 2.7 you should inherit from object
    def __init__(self):
        self.data = []

    def read_from_row(self, row):    # (python naming convention)
        self.data += row             # better way of appending to a list
thebjorn
  • 26,297
  • 11
  • 96
  • 138
0

I'd recommend you step through the code in pythontutor, notice that by putting Data = [] in the class block it is shared between all instances. (Other answers already show how to fix the issue, My goal is to give you a way to understand why the issue is happening)

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59