Reputation: 263
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.
Upvotes: 0
Views: 82
Reputation: 27361
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
Upvotes: 2
Reputation: 21474
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)
Upvotes: 0
Reputation: 1319
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)
Upvotes: 2