The following code demonstrates the difference between mutable and immutable default parameters, and you can see why two of the code produces different results by looking at the memory address and the changes of the default parameters after each function call.
#-*-coding:cp936-*-# The above sentence is for Chinese encoding problem # The default value is only assigned once. This makes it different when the default value is a Mutable object, such as a list, a dictionary, or an instance of most classes. # For example, the following function will accumulate (before) the arguments passed to it during subsequent calls Def F (a,l=[]):p rint (the ' default parameter address is: ' +str (ID (L))) L.append (a) print (' changed parameter address: ' +str (ID (L) ) return l# If you do not want to accumulate parameters, you can define DEF F1 (A,l1=none):p rint (' Default parameter address: ' +str (ID (L1))) If L1 is None:l1=[]l1.append (a) print (' After changing the parameter address is: ' +str (ID (L1))) return l1# Python is a reference assignment, list/dict are mutable type, string/tuple is immutable type # below you can see what the difference between the two code # F test Print (f (1)) Print (' function f ' default parameter is ' +str (f.__defaults__) ') print (f (2)) print (' function f ' default parameter is ' +str (f.__defaults__)) print (f (3)) print (' The default parameter for function f is ' +str (f.__defaults__) ' # F1 test Print (F1 (1)) print (' function f1 default parameter is ' +str (f1.__defaults__) ') print (' F1 (2)) ' Print (' The default parameter for the function F1 is ' +str (f1.__defaults__) ' Print (F1 (3)) print (the default parameter for ' function F1 is ' +str (f1.__defaults__) ')
Operation Result:
C:\users\zzw922cn\desktop>python 1.py The default parameter address is: 56716224 The changed parameter address is: 56716224[1] The default parameter for function f is ([1],) the default parameter address is : 56716224 after changing the parameter address is: 56716224[1, 2] The default parameter of the function f is ([1, 2],) the default parameter address is: 56716224 The changed parameter address is: 56716224[1, 2, 3] The default parameter for function f is ([1, 2, 3],) The default parameter address is: 1525627488 after changing the parameter address is: 56738440[1] Function f1 default parameter is (none,) the default parameter address is: 1525627488 after changing the parameter address is: 56738440[2] Function f1 default parameter is (None,) The default parameter address is: 1525627488 after changing the parameter address is: 56738440[3] Function f1 default parameter is (None,)
Python Learning (vii)--mutable and immutable parameters