I’m writing my first python program and I’m running into something that seems strange.
My program looks like this:
def main():
listOfThings = []
for i in range(0,3):
newThing = thing()
newThing.listOfStrings.append('newString')
listOfThings.append(newThing)
Thing simply looks like this:
class thing:
listOfStrings = []
I’m expecting listOfThings to be:
listOfThings
-thing1
-newString
-thing2
-newString
-thing3
-newString
But instead i’m getting this:
listOfThings
-thing1
-newString
-newString
-newString
-thing2
-newString
-newString
-newString
-thing3
-newString
-newString
-newString
In other languages, this is what I would expect to see if thing.listOfStrings was static. Is there some subtlety of python that I’m missing here?
listOfStringsis a class attribute. All the instances will share the samelistInstead you should add the attribute during
__init__