The use of Python variables is easy to explain.

Source: Internet
Author: User
Python programming often encountered some inexplicable error, in fact, this is not the language itself problem, but we ignore the language itself caused by some of the characteristics, today to see the use of Python variables caused by the 3 magic error, in the future in programming to pay more attention.

1. Variable data type as default parameter in function definition

That seems to be right? You write a small function, for example, to search for a link on the current page and optionally attach it to another provided list.

def search_for_links (page, add_to=[]):    new_links = page.search_for_links ()    add_to.extend (new_links)    Return add_to

On the face of it, it looks like a very normal Python code, and in fact it is, and can be run. However, there is a problem here. If we provide a list for the add_to parameter, it will work as we expect. However, if we let it use the default value, something magical happens.

Try the following code:

DEF fn (var1, var2=[]):    var2.append (var1)    print (VAR2) FN (3) FN (4) FN (5)

Maybe you think we'll see:

[3] [4] [5]

But in fact, what we see is:

[3] [3,4] [3,4,5]

Why is it? As you can see, each time you use the same list, why is the output so? In Python, when we write such a function, the list is instantiated as part of the function definition. When a function is run, it is not instantiated every time. This means that the function will always use exactly the same list object unless we provide a new object:

FN (3,[4]) [4,3]

The answer is as we think. The right way to get this result is to:

DEF fn (var1, Var2=none):    ifnot var2:        var2 =[]    var2.append (var1)

Or in the first example:

def search_for_links (page, add_to=none):    ifnot add_to:        add_to =[]    new_links = Page.search_for_links ()    add_to.extend (new_links)    return add_to

This removes the instantiated content when the module is loaded so that a list instantiation occurs each time the function is run. Note that this is not necessary for non-volatile data types such as tuples, strings, and integers. This means that code like the following is very feasible:

def func (message= "My Message"):    print (message)

2. Variable data type as class variable

This is very similar to the last error mentioned above. Consider the following code:

Class Urlcatcher (object):    URLs =[]    def add_url (self, url):        self.urls.append (URL)

This piece of code looks very normal. We have an object that stores URLs. When we call the Add_url method, it adds a given URL to the store. Looks pretty right, doesn't it? Let's see what's actually going on:

A =urlcatcher () a.add_url (' ') b =urlcatcher () B.add_url (' ') print ( B.urls) print (a.urls)


[' ', ' '] [' ', ' ']

Wait, what's going on?! That's not what we're thinking. We instantiated two separate objects A and B. Gave a URL to a, and the other gave B. How can both of these objects have these two URLs?

This is the same problem as the first one. When you create a class definition, the list of URLs is instantiated. All instances of the class use the same list. In some cases this is useful, but most of the time you don't want to do it. You want each object to have a separate storage. To do this, we modify the code to:

Class Urlcatcher (object):    def __init__ (self):        self.urls =[]    def add_url (self, url):        Self.urls.append (URL)

The list of URLs is now instantiated when the object is created. When we instantiate two separate objects, they will each use two separate lists.

3. Variable Allocation error

This question bothered me for some time. Let's make some changes and use another variable data type-dictionary.

A ={' 1 ': "One", ' 2 ': ' Both '}

Now, let's say we want to use this dictionary somewhere else and keep its initial data intact.

b = ab[' 3 ']= ' three '

Simple, huh?

Now, let's look at the original dictionary a that we don't want to change:

{' 1 ': ' One ', ' 2 ': ' One ', ' 3 ': ' Three '}

Whoa, wait a minute, let's look at B again.

{' 1 ': ' One ', ' 2 ': ' One ', ' 3 ': ' Three '}

Wait, what? A little messy ... Let's think about what happens to other immutable types in this case, such as a tuple:

c = (2,3) d = cd = (4,5)

Now C is (2, 3), and D is (4, 5).

This function results as we expected. So, what exactly happened in the previous example? When you use a mutable type, it behaves a bit like a pointer to the C language. In the above code, we make B = A, and what we really mean is: B becomes a reference to a. They all point to the same object in Python memory. Sounds familiar? That's because the problem is similar to the previous one.

Does the same thing happen to the list? Yes. So how do we fix it? This must be very careful. If we really need to copy a list for processing, we can do this:

b = a[:]

This iterates through and copies a reference to each object in the list, and places it in a new list. Note, however, that if each object in the list is mutable, we will get their references again instead of the full copy.

Assume a list on a sheet of paper. In the original example, a and B are looking at the same piece of paper. If a person modifies the list, two people will see the same change. When we copy references, everyone now has their own list. However, let's assume that this list includes places to find food. If the "refrigerator" is the first in the list, even if it is copied, the entries in the two list also point to the same refrigerator. So, if the refrigerator is modified by a, eat the big cake inside, B will also see the disappearance of this cake. There is no easy way to solve it. As long as you remember it and write the code, use the way that does not cause the problem.

Dictionaries work the same way, and you can create an expensive copy in the following ways:

b = A.copy ()

Again, this will only create a new dictionary that points to the same entries that were originally present. So if we have two identical lists, and we modify a mutable object that is pointed to by a key in dictionary A, these changes will also be seen in dictionary B.

The trouble with the

mutable data types is also where they are powerful. None of the above is an actual problem; they are some of the issues that need to be taken care of to avoid. It is not necessary to use expensive copy operations as a solution in a third project at 99%.

Related Article

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: 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.