Python: defining functions on the fly

后端 未结 3 1733
伪装坚强ぢ
伪装坚强ぢ 2021-02-06 16:09

I have the following code:

 funcs = []
 for i in range(10):
   def func():
      print i
   funcs.append(func)

 for f in funcs:
   f()

The pro

3条回答
  •  日久生厌
    2021-02-06 16:56

    You could try

    for i in range(10):
        def func(j=i):
            print j
        funcs.append(func)
    for f in funcs:
        f()
    

提交回复
热议问题