Python: defining functions on the fly

后端 未结 3 1730
伪装坚强ぢ
伪装坚强ぢ 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:41

    The problem is not that func is being overwritten, it's that the value of i is being evaluated when the function is called, not when it is defined. If you want to evaluate i at definition time, put it in the function declaration, as a default argument to func.

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

    Default arguments are evaluated once, when the function is defined, so the incrementing loop will not affect them. This would work just as well if you used

    def func(i=i):
        print i
    

    but I used the name value to make it clear which name is being used within the function.

    0 讨论(0)
  • 2021-02-06 16:42

    Returning func from another function is safest.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题