Errors that are easy to encounter when setting variables as default values in Python. default values in python

Source: Internet
Author: User

Errors that are easy to encounter when setting variables as default values in Python. default values in python

Think about the following code snippet:
 

def foo(numbers=[]):  numbers.append(9)  print numbers

Here, we define a list (empty by default), add 9 to it and print it out.
 

>>> foo()[9]>>> foo(numbers=[1,2])[1, 2, 9]>>> foo(numbers=[1,2,3])[1, 2, 3, 9]

Does it look okay? But when we do not enter the number parameter to call the foo function, the magic thing happens:
 

>>> foo() # first time, like before[9]>>> foo() # second time[9, 9]>>> foo() # third time...[9, 9, 9]>>> foo() # WHAT IS THIS BLACK MAGIC?![9, 9, 9, 9]

So, what is the situation? Intuition tells us that no matter how many times we do not enter the number parameter to call the foo function, 9 here should be allocated to an empty list. This is wrong! In Python, the default value of a function is instantiated when the function is defined, rather than called.

We will still ask why the default value is assigned different values when the function is called? Because every time you specify a default value for a function, Python stores this value. If you override the default value when calling a function, the stored value will not be used. If you do not override the default value, Python will make the default value reference the stored value (numbers in this example ). It does not copy the stored values to assign values to this variable. This concept may be difficult for beginners to understand, so it can be understood as follows: There are two variables: one is internal and the other is the current runtime variable. The reality is that we have two variables for interaction with the same value, so once the value of numbers changes, it will also change the record of the initial value stored in Python.

The solution is as follows:
 

def foo(numbers=None):  if numbers is None:    numbers = []  numbers.append(9)  print numbers

Generally, when people hear this, they will ask another question about the default value. Think about the following program:
 

def foo(count=0):  count += 1  print count

When we run it, the results are exactly what we expected:
 

>>> foo()1>>> foo()1>>> foo(2)3>>> foo(3)4>>> foo()1

Why? The secret is not when the default value is assigned, but the default value itself. An integer is an unchangeable variable. Unlike the list type, Integer Variables cannot be changed during function execution. When count + = 1 is executed, the original value of count is not changed. Instead, count points to different values. However, when we execute numbers. append (9), we change the original list. As a result, this result is returned.

The following is another problem that will occur when default values are used in functions:
 

def print_now(now=time.time()):  print now

Same as above, time. the value of time () is variable, so it will only be calculated when the function is defined, no matter how many calls, will return the same time-the output time here is the time when the program is interpreted by Python.

>>> print_now()1373121487.91>>> print_now()1373121487.91>>> print_now()1373121487.91

* This problem is similar to its solution in Python 2.x and 3.x. It is the only difference in Python 3.x, yes. The print expression in it should be the function call method (print (numbers )).

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