Python provides the sequence type (strings, tuples, and lists are all sorted types), and provides special syntax to facilitate operations on these types. The most common operations are slice. Objects of the same ordered type support the "+" operator to connect to a new ordered object. Ordered objects can also be multiplied by an integer to obtain a new ordered object. During debugging, I often use this statement to print a split line: print '-' * 50. Be careful when performing the "*" or "+" Operation on the ordered type. Today, my colleagues encountered a very depressing problem. See the following code:
# Coding = gbkclass point (object): def _ init _ (self, x, y): Self. X = x self. y = y def _ repr _ (Self): Return '(% d, % d)' % (self. x, self. y) itemlist = [point (-1,-1)] * 5 # assign values to the list elements
for i in range(5): itemList[i].x = i itemList[i].y = i print itemList
The code above creates a list containing five point objects, and then assigns values to the attributes of each object in the list in a for loop. Run the above code. What is the result displayed on the screen? Is it [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4? This code fool us all. Result: [(4, 4), (4, 4), (4, 4), (4, 4), (4, 4)]. Why? The answer is the reference type and value type. [Point (-1,-1)] * 5 returns a list containing five elements. The elements in the list actually reference the same object, when the for loop is used to initialize the list, the value of the same object is actually modified. So the result is ...... At first, we were depressed for a long time and no one was aware of the problem. After debugging for a long time, I found out that, oh, God was here. As long as you make a simple modification, the result will be what we want:
# ...# itemList = [Point(-1, -1)] * 5itemList = [Point(-1, -1) for i in range(5)]# ...