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.

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

You probably want to capitalize numbers if you're making a point of showing python naming conventions.
@pvg I was trying not to, but you're right and I've updated the code.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.