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?
Use functools.partialin conjunction with a dictionary in this situation.
functools.partial
, , .
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
; . , i , . - , , , for. , addi i.
i
for
addi
, addi , . addi , . ; (, )? , d jpp. , ?
d
, , , , . :
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 - .
globals
n
operator.add
:
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/...
?
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
, , . , , :
>>> 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 , " " .
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
Source: https://habr.com/ru/post/1695703/More articles:How to configure Unity 2017.4 for Android and avoid build failures in OSX? - javatypescript dynamic parameter interface does not compile without any - typescriptMerge Git branches based on a specified commit pair as a common base - gitdjango objects.all () vs objects.filter () - pythonкогда "bash -c" приведет к созданию дочерней оболочки? - linuxAutomatic decorator methods - c #How to use a variable as a function name in Python - pythonIterate over class members - c ++Unsubscribe from an event of a general class whose type parameter is specified in the general method - genericsETS creation return value - referenceAll Articles