Python list hidden big pits

Source: Internet
Author: User
Tags python list

Today, when writing a piece of code, I found that when defining a class property, we encountered a very strange problem.

How weird is that? Take a look at the following code, I define a class:

class # Define a text message class    # set a content property, which is a list to store SMS    def Add (self,text):# Add SMS        self.content.append (text)
>>> obj1=SMS ()>>> obj1.add (" SMS Content 1")>>> obj1.content[' SMS content 1']>>>

We created the instance obj1 and added an element to the content property. Here we create the instance obj2:

>>> obj2=SMS ()>>> obj2.add (" SMS Content 2")>>> Obj2.content# print it again, eh? The strange phenomenon has appeared! [' SMS content 1' SMS Content 2']>>>

We know that creating two different instances of the same class, modifying the properties of one instance, does not affect another instance.

But in this code, we are surprised to find that the content attribute of the obj1 to add an element ' text message Contents 1 ', this element actually appears in the Obj2 content attribute!

It's haunted .... Remember at that time I stared at the code to see a half-day, also did not figure out how the matter, ha in fact, I just learned python, this problem is really very abusive heart, this and the basic concept of OOP clearly inconsistent with it! Is there a bug in the Python interpreter?

After a few of my toss, finally found the problem lies. Truth, only one!

That is, the content property of the Obj1 instance and the Obj2 instance is actually the same list! More precisely, these two properties point to the same list Object!

"Add after Pit"

Python list hidden big pits

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.