Problems caused by the default value of the Functions

Source: Internet
Author: User
Tags print object

As a dish, I learned a little bit about py. I used variable data types as function parameters. What is variable data type? Let's talk about the code later:

Def f (x = []): x. append (1) print id (x) # print Object ID (each object has its own memory id) return x
Output:

>>> print f()47356040[1]>>> print f()47356040[1, 1]>>> 

You must have a question. Why are two elements printed on the list object? Well, it's not too early for me to bypass the circle, because the variable type is used as the default parameter, another problem is that python functions with default parameters are initialized at the time of definition (completely different from C ++ ), the result is that when a function is called without passing parameter overwrites, the python interpreter saves the original default initialized parameters and only saves one copy of the default values, if f () is called once, a 1 is added to the initialized empty list. After two calls, the internal variable of the function is changed to two elements.

Next:

>>> Def f (x = []): x. append (1) print id (x) # print Object idreturn x >>> print f () 47356040 [1] >>> print f () 47356040 [1, 1] >>> print f (t = [2]) # The original default variable name must be used. This also indicates that the interpreter is used to prevent x loss, the reason is that x already has Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
Print f (t = [2]) TypeError: f () got an unexpected keyword argument 'T' >>> print f (x = [2]) 47350792 [2, 1] >>> print f () 47356040 [1, 1, 1] >>>
  
 
Here, we can clearly see that the python interpreter keeps saving this default value (object) for us. If there is a real parameter overwrite (here the overwrite is not appropriate, it should be replaced ), we can see from the id change that the variables passed by the outside are preferentially used, but the internal variables (not destroyed, because the pointer reference count is always greater than zero, = 1)

Next let's look at the following:

>>> Def f (x = 0): x + = 1 print id (x) return x >>> print f () 334147601 >>> print f () 334147601 >>> print f (t = 2) # in the same case, the default parameter name (same as the cause) Traceback (most recent call last) is specified"
 
  
", Line 1, in
  
   
Print f (t = 2) TypeError: f () got an unexpected keyword argument 'T' >>> print f (x = 2) 334147123 >>> print f () 334147601 >>> print f (x = 3) 334146884 >>> print f () 334147601 >>>
  
 
For the above problem, the returned value remains unchanged when no parameter function is called, and it is the same value 1 of the same id (one initialization, the IDS of different parameters are different (the red value). Why? It is actually quite simple, because integer is an unchangeable data type. Unlike list, integer variables are similar to string constants in C ++ In the python interpreter, cannot be modified (not in the original location, x + = 1, x id (x) will change, we did not actually change the value of the original location ), the only way is to re-instantiate an object and point the original pointer. Therefore, different parameters are passed with different IDs ()

The following is a simple example:

>>> a=[1]>>> b=a>>> id(a)47361544L>>> id(b)47361544L>>> a.append(2)>>> b[1, 2]>>> a is bTrue
The reason above is that the variable type object Value assignment is to pass the reference, and no new object is instantiated.

Finally, let's talk about the initial foreshadowing, variable data types and immutable data types:

Here is a lot different from C/C ++. First, all the variables in Python are reference values, that is, the declared variables point to their values through binding, here, the immutable data type means that the bound value is immutable. For those immutable variables, if you change the value such as count + = 1, the interpreter creates a new value, binds the variable to the new value, and the pointer reference of the old value is gone (the pointer reference count is reduced to 0) it will be recycled by the garbage collection mechanism. an unchangeable data type also has a feature that can calculate its hash value (which has been used for a long time, but I did not expect it ), in this way, it can be further used as the key of the dictionary element (if it is a nested dictionary, it may also be the element of the dictionary element). When a variable type of data object is operated, you do not need to re-apply for memory elsewhere. You only need to apply for the memory continuously after this object. Undo (+/-) is OK, that is, his first address remains unchanged, however, the length of the memory area will change (this is when the continuous memory application is successful, if it is successful, it will be re-installed with New fast space), haha, in fact, these containers, Dictionary bottom layer It is nothing more than array, linked list, binary tree, and other data structures plus algorithms. Therefore, the basics of C ++ need to be useful! Hey.

List the variable data types in python: list, dict

Unchangeable data types: int, string, float, tuple


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.