user1583531
user1583531

Reputation: 3

difference in list.append and list addition in class instances

I wish I could better title the question.
Anyway, Here is test.py

class test(object):
    tags = []
    def __init__(self):
       self.tags= self.tags + ['tag']

testA= test()
testB = test()

print testA.tags

Here is the output:

['tag']

Now I change class test to

class test(object):
    tags = []
    def __init__(self):
        self.tags.append('tag')

Here is the output:

['tag', 'tag']

I expected the first result ['tag'] in both cases.

Upvotes: 0

Views: 67

Answers (1)

ovgolovin
ovgolovin

Reputation: 13410

self.tags + ['tag'] creates a new object. And then it is assigned to self.tags.

self.tags.append works with the same tags object from the class. So all the objects share the same tags object and append to it.

Upvotes: 1

Related Questions