0

Please consider

class A(object):
    def __init__(self, a):
        self.a = a


funcs = []
for i in range(5):
    a = A(i)
    funcs.append(lambda: a.a)

for func in funcs:
    print(func())

This code outputs

4
4
4
4
4

because the name a is bound within the outer scope only once, and only the last one is dereferenced (by name) from every func at the time they are called.


What is the most Pythonic way to achieve the straight-forward-expected

0
1
2
3
4
Gulzar
  • 17,272
  • 18
  • 86
  • 144
  • There are probably many other duplicate questions, all of which point at a few standard ways to solve the problem. "Most Pythonic" is opinion-based and thus off topic. – Karl Knechtel Jul 13 '21 at 17:37

0 Answers0