Can't figure out how Python binds variables in closures.
Look at this example:
>>> def create_multipliers(): ... return [lambda x : i * x for i in range(5)] >>> for multiplier in create_multipliers(): ... print multiplier(2) ...
Expect the following output:
0
2
4
6
8
But actually get this:
8
8
8
8
8
Instance Extension:
# coding=utf-8 __author__ = 'xiaofu' # Explanatory references /en/latest/writing/gotchas/#late-binding-closures def closure_test1(): """ The output of each closure is the same i value :return. """ closures = [] for i in range(4): def closure(): print("id of i: {}, value: {} ".format(id(i), i)) (closure) # Python's closures are late binding. # This means that the values of variables used in closures are looked up at the time the inner function is called. for c in closures: c() def closure_test2(): def make_closure(i): def closure(): print("id of i: {}, value: {} ".format(id(i), i)) return closure closures = [] for i in range(4): (make_closure(i)) for c in closures: c() if __name__ == '__main__': closure_test1() closure_test2()
Output.
id of i: 10437280, value: 3 id of i: 10437280, value: 3 id of i: 10437280, value: 3 id of i: 10437280, value: 3 id of i: 10437184, value: 0 id of i: 10437216, value: 1 id of i: 10437248, value: 2 id of i: 10437280, value: 3
to this article on how Python newbie closure bind variable operation is introduced to this article, more related Python closure bind variable example content, please search my previous posts or continue to browse the following related articles I hope you will support me more in the future!