Return function
The return object of a function can be a function, which is not executed immediately when it returns, but is executed when the return object is called
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
>>> f1 = lazy_sum(1, 3, 5, 7, 9)
>>> f2 = lazy_sum(1, 3, 5, 7, 9)
>>> f1==f2
False
When the lazy_sum
function sum
is returned , the relevant parameters and variables are stored in the returned function, which is called Closure.
Try to avoid referencing loop variables in the closure, otherwise problems may occur
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
>>> f1()
9
>>> f2()
9
>>> f3()
9
#解决办法 是另外定义一个函数 固定住参数
def count():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
>>> f1, f2, f3 = count()
>>> f1()
1
>>> f2()
4
>>> f3()
9
#
def createCounter():
num = 0
def counter():
nonlocal num
num=num+1
return num
return counter
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!')
Use the closure to return a counter function, each time it is called, it returns an incrementing integer;
nonlocal means global variable
Anonymous function
An anonymous function has only one expression, so you don’t need to worry about function name conflicts and call it directly; lambda x, x represent parameters;
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
L = list(filter(lambda n: n % 2 == 1, range(1, 20)))
print(L)#打印奇数
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Decorator
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
#@语法,把decorator置于函数的定义处
@log
def now():
print('2015-3-25')
>>> now()
call now():
2015-3-25
wrapper()
The parameter definition of the function is (*args, **kw)
, therefore, the wrapper()
function can accept calls with arbitrary parameters. In the wrapper()
function, first print the log, and then call the original function.
More complicated usage:
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
#__name__等属性复制到wrapper()
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
Design decorator, it can act on any function, and print the execution time of the function:
import time, functools
def metric(func):
@functools.wraps(func)
def wrapper(*args, **kw):
s = time.time()
x = func(*args, **kw)
e = time.time()
print('%s executed in %s ms' % (func.__name__, (e-s)*1000.0))
return x
return wrapper
# 测试
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y;
@metric
def slow(x, y, z):
time.sleep(0.1234)
return x * y * z;
f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
print('测试失败!')
elif s != 7986:
print('测试失败!')
Partial function
functools.partial
The role of is to fix certain parameters of a function (that is, set the default value), return a new function, and call this new function easier.
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
Reference source: https://www.liaoxuefeng.com/wiki/1016959663602400/1017454145929440