why list in object is not showing correctly in python [duplicate]
Possible Duplicate:
Assign a value to class variable is assiging it for all instances of that object
I need a help. I am used to java development and new I am starting python. And I write a simple class which contain a list of string. and In the main function I create a list of this object and I would like to print the content of the list of object. But my function print all the string of all the object together. Here is an example
class FastData:
name=''
开发者_StackOverflow lines=[]
def __init__ (self, name):
self.name=name
def setName(self,name):
self.name = name
def addLine(self, line):
self.lines.append(line)
def getLines(self):
return self.lines
def getName(self):
return self.name
def printList(self):
for myline in self.lines:
print myline
if __name__ == '__main__':
listes = []
newData = FastData("Single")
newData.addLine("1")
newData.addLine("2")
listes.append(newData)
newData1 = FastData("Double")
newData1.addLine("111")
newData1.addLine("222")
listes.append(newData1)
for myList in listes:
print myList.getName()
myList.printList()
and Here is what I got like output
Single
1
2
111
222
Double
1
2
111
222
Thank for your help
Thathug
In your code, all instances of FastData
share the same lines
object. Fix it like so:
class FastData:
# note that I've removed `name' and `lines' from here
def __init__ (self, name):
self.name = name
self.lines = []
The reason your code worked the way it did was that lines
was a property of the class, not of each individual instance of the class.
精彩评论