Capturing Variables in Lambda Functions
When using lambda functions within a loop, it's important to understand their variable scope. Unlike regular functions which copy local variables, lambda functions reference them.
Consider the given code:
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
Here, the lambda function captures the value of m from the enclosing scope. However, after the loop finishes, m retains the last value ('mi'). When each lambda function is called, it references this shared m variable, resulting in the output "mi" multiple times.
To overcome this issue and ensure each lambda captures a distinct value of m, use a technique called "default arguments":
for m in ('do', 're', 'mi'):
funcList.append(lambda m=m: callback(m))
By making m a default parameter with the same name, each lambda captures its own instance of the variable, ensuring the expected output:
"do"
"re"
"mi"
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3