import multiprocessing
def process1():
return 1
def process2():
return 2
p1=multiprocessing.Process(target=process1)
p2=multiprocessing.Process(target=process1)
p1.start() #启动
p2.start()
p1.join() #在主程序中等待相应进程完成
p2.join()
def line_out():
def line(x):
return x+1
my_line=line_out()
print(my_line(2)) #3
函数定义中引入外部变量
def line_out():
b=10
def line(x):
return x+b
b=1
return line
my_line=line_out()
print(my_line(5)) #6
line和b构成了闭包
再来一个例子
def line_out(a,b):
def line(x):
return a*x**2+b
return line
line1=line_out(1,2) #x^2+2
line2=line_out(2,3) #2x^2+3
def decorate(old_func):
def new_func(a,b):
print("input",a,b)
return old_func
return new_func
@decorate
def add(a,b): #将函数作为参数传递给decorate( )
return a+b
@decorate
def divide(a,b):
return a-b
if __name__=="__main__":
print(add(1,2)) #add=decorate(add)
#add(1,2)
print(divide(1,2))
装饰器也可以带参,定义和@处加参数即可
装饰类:
def decorate_class(someClass):
class new_class(object):
def __init__(self,age):
self.total_display = 0
self.wrapped = someClass(age)
def display(self):
self.total_display += 1
print("total dispay:",self.total_display)
self.wrapped.display()
return new_class
@decorate_class
class bird:
def __init__(self,age):
self.age=age
def display(self):
print("age:",self.age)
if __name__=="__main__":
chicken=bird(3)
for i in range(3):
chicken.display()
结果 :
total display:1
age:3
total display:1
age:3
total display:1
age:3
lambda_sum=lamda x,y:x+y
print(lambda_sum(1,2))
lis=[6,7,3,4]
res=map(lambda x:x+3,lis) #第二个为可循环对象
print(list(res)) #[9,10,6,8]
或:
lis1=[1,3,5,6]
lis2=[1,3,5,6]
def add(x,y):
return x+y
res=map(add,lis1,lis2) #2,6,10,12
def larger(a):
if a>100:
return True
else:
return False
for i in filter(larger,[1,101,99,20]):
print(i) #101
from functools import reduce
lis=[1,2,3,4,5]
res=reduce(lambda x,y:x+y,lis) #函数累进的作用于各个参数
print(res) #15
生成器: gen=(x for x in range(3))
列表:lis=[x**2 for x in range(3)]
x1=[1,2,3,4]
y1=[2,3,4,5]
lis=[x**2 for (x,y) in zip(x1,y1) if y>4]
词典: dic={k : v for k,v in enumerate("scar") if v not in"sc"}
print(dic) # {2:a, 3:r}