python基礎学習ノート(五)装飾器、高級関数
3227 ワード
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
リスト: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}