How to use a loop variable closure function

In general, the function body closure is to avoid a loop variable, because the main function call, the loop variable end is generally performed, a return value after execution.

def count():
fs = []
for i in range(1, 4):
    def f():
         return i*i
    fs.append(f)
return fs

f1, f2, f3 = count()
print(f1(),f2(),f3())
  • The results are expected to return 1,4,9, but the results actually returned is 9,9,9
  • The reason is that when the count () function returns the three functions, the value of this variable is referenced three functions has become a 3 i

Big Box  How closures function uses a loop variable "title =" Solution a "> a solution

  • Methods: The problem is that because the function only when executed to acquire the outer parameter i, if i can get to the function definition, the problem can be solved. And acquires the default parameters can be done precisely without definition function when the input parameter values ​​and i running function, the () to the definition of f (m = i) in the function f, the function f to return values ​​to m * m.
  • Code changes:

    def count():
    fs = []
    for i in range(1, 4):

    def f(m = i):
        return m * m
    fs.append(f)
    

    return fs

    f1,f2,f3 = count()
    print(f1(),f2(),f3())
    1,4,9

Guess you like

Origin www.cnblogs.com/lijianming180/p/12037927.html