Modifying class members in Python

tr244 :

I have a small piece of code where I am trying to change the member values of an array of class objects.

class Test(object):
    def __init__(self):
        self.id = 0

test = []
temp = Test()

for i in range(5):
    temp.id = i
    test.append(temp)
    print(test[len(test)-1].id)

print()

for i in range(5):
    print(test[i].id)

However, I am getting the following result and I'm unable to figure out why? Any help is appreciated.

0
1
2
3
4

4
4
4
4
4
EPH :

This is normal. You filled test with the same object at each step and you are modifying this object. Whenever you do a modification all the references of the object are modified. To see this you can print the id of temp at each step

class Test(object):
    def __init__(self):
        self.id = 0

test = []

for i in range(5):
    temp = Test()
    temp.id = i
    test.append(temp)
    print(test[len(test)-1].id)

for i in range(5):
    print(test[i].id)

And the output will be:

0
1
2
3
4

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=376221&siteId=1