python function Tutorial: python default trap parameters problem

This article is to tell you about the issue of default parameters python traps, there is little need partners can refer to
is the default function parameters of the problem of python inside a common pitfalls. as follows:

def func(mylist = []):
  mylist.append(1)
  return mylist

The following execution results are as follows:

print func()
print func()
print func()
print func(['a'])
print func()

The results are as follows:

[1]
[1, 1]
[1, 1, 1]
['a', 1]
[1, 1, 1, 1]

So the results, the first three can be seen if the parameter is not specified, then every time a function call, mylist call is the same object. This is because the default parameters of the function, the code is compiled into PyCodeObject time, they have created object pointer, and there is within func_default the function. After the code is run, call functions, if no parameter is specified, then each call, then the argument pointer variables are variable code compilation phase of the specified object.

print func.func_default

In this case the result is:

([1, 1, 1, 1],)
the default parameters of two cases:

The default parameter values are immutable object
at this time func_default function it has been directed to the same subject, if the internal function modifies the variable, then the default argument will point to a new immutable objects.
But func_default unchanged. And each call functions are read func_default, therefore each time the same.

In [30]: def func2(var = 1):
  ....:   var += 1
  ....:   return var
  ....: 
 
In [31]: func2()
Out[31]: 2
 
In [32]: func2()
Out[32]: 2
 
In [34]: func2.func_defaults
Out[34]: (1,)

The default parameter is mutable objects, such as list, dict, class, etc.
In this case, if you modify the object pointer in the function (not create new objects), then func_default will change. This is the beginning of mylist causes of change. Look at the following examples:

In [35]: def func(mylist = []):
  ....:   mylist = []  #这里 创建了新的对象,
       mylist.append(1)
       return mylist
 
In [44]: func()
Out[44]: [1]
 
In [45]: func.func_defaults
Out[45]: ([],)

Because the object is created, mylist just as a new target alias exists behind the changes have been nothing to do with func_default.
A default application parameters

Look at a classic example below:

def outer():
  res = []
  for i in range(4):
    def inner(j):
      return j * i
    res.append(inner)
  return res
 
print [m(2) for m in outer()]

# Abridged version:

def multipliers():
  return [lambda x : i * x for i in range(4)]
print [m(2) for m in multipliers()]

As a result [6, 6, 6, 6], instead of [0, 2, 4, 6], because binding is to delay closure. In addition function is bound variable instead of the value bindings. When the end of the cycle, has the value of i is 3, 6. In this case the result is a solution that is, the default value parameter binding. The following changes:

def outer():
  res = []
  for i in range(4):
    def inner(j, i = i):
      return j * i
    res.append(inner)
  return res
 
print [m(2) for m in outer()]

# Abridged version:

def multipliers():
  return [lambda x, i = i : i * x for i in range(4)]
print [m(2) for m in multipliers()]

In this case, using the default parameters in the code compile time, it gave the parameters wrote func_default function, you can bind a 0,1,2,3. It was natural that

[0, 2, 4, 6]
This is an application default parameters.

Above and a modified form generator

def multipliers():
  return (lambda x, i = i : i * x for i in range(4)) #修改成生成器
print [m(2) for m in multipliers()]

Finally, we recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, there is a chance of business experience, and calmed down to zero on the basis of information to project combat , we can at the bottom, leave a message, do not know to put forward, we will study together progress

Published 34 original articles · won praise 51 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104806237