Using a for loop to define multiple functions - Python

Suppose I need to create 10 functions called add1, add2, ..., add10. For each I addi takes an integer x and prints x + i.

Python gave me a NameError when I tried the following and appreciated add2 (10).

for i in range(10):
    def addi(x):
        return x + (i+1)

I know that the code above is incorrect, because the addi functions that I defined do not change; I am pretty sure that all I did was override addi 10 times. How can you quickly identify these 10 functions?

+3
source share
6 answers

Use functools.partialin conjunction with a dictionary in this situation.

, , .

from functools import partial

def add(x, i):
    return x + i

d = {'add'+str(k): partial(add, i=k) for k in range(1, 10)}

d['add3'](5)  # 8

  • .
  • functools.partial - , .
+2

; . , i , . - , , , for. , addi i.

, addi , . addi , . ; (, )? , ​​ d jpp. , ?

, , , , . :

def addfunc(n):
    def addn(x):
        return x+n
    return addn

for i in range(1,10):
    globals()['add{}'.format(i)] = addfunc(i)

globals, n. operator.add - .

+1

:

from types import FunctionType
from copy import copy

def copy_function(fn, name):
    return FunctionType(
    copy(fn.func_code),
    copy(fn.func_globals),
    name=name,
    argdefs=copy(fn.func_defaults),
    closure=copy(fn.func_closure)
)

for i in range(10):
    name = 'add' + str(i)
    def _add(x):
        return x + (i+1)
    globals()[name] = copy_function(_add, name)


print add1(2) # 4
print add3(8) # 12 

fooobar.com/questions/1695705/...

+1

?

def createFunc(i):
  def func(x):
    return x + (i+1)
  return func

:

add = [createFunc(i) for i in range(10)]
print add[0](1)  # 1+(0+1) = 2
print add[0](2)  # 2+(0+1) = 3
print add[2](10) # 10+(2+1) = 13
print add[2](11) # 11+(2+1) = 14
0

, , . , , :

>>> def f(x, i):
...     return x + i + 1
... 
>>> from functools import partial
>>> for i in range(10):
...     globals()['add%s' % i] = partial(f, i=i)
... 
>>> add8(5)
14
>>> add3(5)
9

functools.partial currying Python , " " .

0

I would suggest:

for i in range(10):
    exec('def add'+str(i)+'(n): return n + '+str(i))

This example uses just plain exec after constructing the function definition as a string.

:

add4(3)
7
0
source

Source: https://habr.com/ru/post/1695703/


All Articles