Neglected Python syntax

Source: Internet
Author: User

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)]# ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.