博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python使用(三)
阅读量:4608 次
发布时间:2019-06-09

本文共 8077 字,大约阅读时间需要 26 分钟。

1.function_option.py

2.function_code_option.py
3.thread_option.py
4.class_option.py
5.threading_option.py
6.producer_conusmer_option.py

 

1.function_option.py

1 # coding=utf8 2 __author__ = 'SummerChill' 3  4 #一般函数 5 def my_abs(x): 6     """this is a abs method""" 7     if isinstance(x,int): 8         if x>=0: 9             return x10         else:11             return -x12 #函数调用13 print(my_abs('ss'))#None14 print(my_abs(-12))#1215 16 #空函数 类似于占位符的概念,这个函数没有写完,别人也可以调用而且调用不报错.17 def nop():18     pass19 20 nop()21 22 ####python函数可以没有返回值,如果没有则默认为None23 24 #多值函数25 #函数可以有多个值 多个值以元组的方式来展示的,获取后不允许修改返回值。26 def multi(x,y):27     return x,x+y28 29 data=multi(1,2)30 print(data)#(1, 3)31 print(data[1])#332 33 def add(x,y,f):34     return f(x)+f(y)35 #函数可以作为变量 传入时只传入函数名称[去掉自动添加的()]36 print(add(1,2,my_abs))#337 print(add(1,2,lambda x:x+1))#538 #lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x+1为函数39 40 #默认的参数 注意:非默认参数不能在默认参数的后面41 #用户传入则以用户的为准,否则取默认值42 def defalut(x,y=1,z=2):43     return x+y+z44 print(defalut(1))#445 print(defalut(1,3))#646 47 #可变的参数 可变参数的接受端 是以tuple方式接受的48 #常规的参数不能在可变的参数的后面49 def change(x,*y):50     total=051     for i in y:52         total=total+i53     return x,total54 print(change(1,1,2,3,4,5))#(1, 15)55 56 ###########调用函数时57 #对号入座58 print(multi(1,2))#(1, 3)59 print(multi(2,1))#(2, 3)60 #直接指定参数 养成好的习惯61 print(multi(y=2,x=1))#(1, 3)
View Code

 

 

2.function_code_option.py

1 # coding=utf8 2 __author__ = 'SummerChill' 3  4 #lamda 5 add=lambda x,y:x+y 6 print(add(1,2))#3 7  8 #apply 使用参数来触发方法并且获取返回值。一般了解就可以 9 #第一个方法的名称10 #方法中的一般的参数11 #方法中的可变参数12 def addnew(x,y,**z):13     print(z,x,y)14 15 def addold(x,y):16     print(x,y)17 apply(addnew,[1,2],{
'a':1,'b':2})#({'a': 1, 'b': 2}, 1, 2)18 apply(addold,[1,2])#(1, 2)19 20 #filter 过滤函数[返回布尔类型]和要过滤的seq集合21 #sequence:list,tuple,set,string,dic22 #返回值:list string tuple23 def filterfun(x):24 if int(x)%2==0:25 return True26 else:27 return False28 29 print(filter(filterfun,[1,2,3,4,5,6,7,8,9]))#[2, 4, 6, 8]30 print(filter(filterfun,(1,2,3,4,5,6,7,8,9)))#(2, 4, 6, 8)31 print(filter(filterfun,set([1,2,3,4,5,6,7,8,9])))#[2, 4, 6, 8]32 print(filter(filterfun,'123456789'))#246833 print(filter(filterfun,{
'1':'A',2:'B',3:'C'}))#[2]34 35 #map 将传入的seq 进过一个mapfun函数计算得到一个新的list36 #返回值都有list37 def map_fun(x):38 return 2*int(x)39 40 print(map(map_fun,[1,2,3,4,5,6,7,8,9]))#[2, 4, 6, 8, 10, 12, 14, 16, 18]41 print(map(map_fun,(1,2,3,4,5,6,7,8,9)))#[2, 4, 6, 8, 10, 12, 14, 16, 18]42 print(map(map_fun,set([1,2,3,4,5,6,7,8,9])))#[2, 4, 6, 8, 10, 12, 14, 16, 18]43 print(map(map_fun,'123456789'))#[2, 4, 6, 8, 10, 12, 14, 16, 18]44 print(map(map_fun,{
'1':'A',2:'B',3:'C'}))#[2, 4, 6]45 46 #两个参数还是map 是两个序列的聚合47 #不改变单个序列的元素个数48 #在map函数为多个参数中,两个序列分别传给对应的参数,49 # 如果有一方个数不足,则默认为None50 def map_fun_new(x,y):51 if x is None:52 x=053 if y is None:54 y=055 return int(x)+int(y)56 print(map(map_fun_new,(1,2,3,4),[1,2]))#[2, 4, 3, 4]57 58 59 #reduce60 def reuduce_fun(x,y):61 return x,y62 63 #先将序列中的前两个带入计算,然后将计算结果a和第三个元素带入计算,一次迭代64 #如果指定了initial则首先从此值和第一个元素开始计算。65 print(reduce(reuduce_fun,[1,2,3,4,5,6,7,8,9]))#((((((((1, 2), 3), 4), 5), 6), 7), 8), 9) 最终是一个大的tuple66 print(reduce(reuduce_fun,[1,2,3,4,5,6,7,8,9],10))#(((((((((10, 1), 2), 3), 4), 5), 6), 7), 8), 9)67 68 ##################异常的处理69 try:70 print 'try...'71 r = 10 / 072 print 'result:', r73 except Exception as e:74 print 'except:', e #except: integer division or modulo by zero75 #raise #一旦执行了raise语句,raise后面的语句将不能执行(和Java中throw一样) #ZeroDivisionError: integer division or modulo by zero76 #print("end raise")77 finally:78 print 'finally...'79 print 'END'
View Code

 

 

3.thread_option.py

1 # coding=utf8 2 __author__ = 'SummerChill' 3  4 import thread,time 5 #主线程退出则此线程会终止 6 lt=thread.allocate_lock() 7 def sayHi(): 8     print(time.ctime()+"------"+str(thread.get_ident()),"hi") 9     print(time.ctime()+"------"+str(thread.get_ident()),"is locked:"+str(lt.locked()))10     print(time.ctime()+"------"+str(thread.get_ident()),"begin get lock")11     #尝试着去获取锁 参数为watiFlag True表示如果此锁被其他人占用则等待12     #如果为False则不等待,如果有其他线程占用 获取失败13     lt.acquire(True)14     time.sleep(5)15     print(time.ctime()+"------"+str(thread.get_ident()),"end get lock")16     print(time.ctime()+"------"+str(thread.get_ident()),"begin release lock")17     #释放锁18     lt.release()19     print(time.ctime()+"------"+str(thread.get_ident()),"end release lock")20     # thread.interrupt_main()21 thread.start_new_thread(sayHi,())22 time.sleep(2)23 thread.start_new_thread(sayHi,())24 25 #10s后main线程自动关闭26 try:27     time.sleep(10)28 except KeyboardInterrupt:29     print('我被打断了')30 finally:31     print('done')32 """33 ('Thu Sep 22 08:48:57 2016------11432', 'hi')34 ('Thu Sep 22 08:48:57 2016------11432', 'is locked:False')35 ('Thu Sep 22 08:48:57 2016------11432', 'begin get lock')36 ('Thu Sep 22 08:48:59 2016------10712', 'hi')37 ('Thu Sep 22 08:48:59 2016------10712', 'is locked:True')38 ('Thu Sep 22 08:48:59 2016------10712', 'begin get lock')39 ('Thu Sep 22 08:49:02 2016------11432', 'end get lock')40 ('Thu Sep 22 08:49:02 2016------11432', 'begin release lock')41 ('Thu Sep 22 08:49:02 2016------11432', 'end release lock')42 ('Thu Sep 22 08:49:07 2016------10712', 'end get lock')43 ('Thu Sep 22 08:49:07 2016------10712', 'begin release lock')44 ('Thu Sep 22 08:49:07 2016------10712', 'end release lock')45 done46 """
View Code

 

 

4.class_option.py

1 # coding=utf8 2 __author__ = 'SummerChill' 3  4 """ 5 定义的关键字:class。 6     一个类里的初始化方法__init__(self,?),第一个参数必须是self。 7     这是构造方法。内部的方法第一个参数也要是self,self相当于java对象里的this。 8  9 注:10 一个类里只识别一个__init__(self,?)方法。11 如果有多个则后者覆盖前者。12 即:如果一个类中有名字重复的函数。13 不论参数个数是否一致只识别最后一个。。14 """15 class Person:16     name=''17     def __init__(self):18         pass19     def __init__(self,_name):20         print('ss')21 22     def say(self):23         print("Person%s"%(self.name))24     def say(self,id):25         print("Person%s %s "%(self.name,id))26 p=Person('zenith')27 p.say(1)28 #python 里没有方法重载问题 后者覆盖前者29 30 class Man(Person):31     id=''32     def __init__(self,_id,_name):33         self.id=_id34         self.name=_name35     def say(self):36         print("Man %s %s "%(self.name,self.id))37 38 m=Man(1,'man')39 m.say()40 #如果一个成员变量或者方法,父类有子类也有则子类覆盖父类的成员变量或者方法。
View Code

 

 

5.threading_option.py

1 # coding=utf8 2 __author__ = 'SummerChill' 3 import threading,time 4  5 class Worker(threading.Thread): 6     def __init__(self): 7         # 如果自定义了构造函数则要将threading.Thread初始化。 8         #AssertionError: Thread.__init__() not called 9         threading.Thread.__init__(self)10 11     def run(self):12         print(self.getName())13         print('begin hi')14         time.sleep(5)15         print('end hi')16         print(self.isAlive())17         #是否为守护线程18         print(self.isDaemon())19 20 print('main begin')21 th=Worker()22 th.setName('th_hi')23 #守护线程:如果用户线程都死亡了,此线程亦会终止,和main主进程没有任何关系.24 th.setDaemon(False)25 th.start()26 #join 不加参数会等当前线程在等待join的线程结束后再继续,timeout 参数最多等n秒27 th.join()28 print('main end')
View Code

 

 

6.producer_conusmer_option.py

1 # coding=utf8 2 __author__ = 'SummerChill' 3  4 import threading,Queue,time,random 5  6 #练习:一个线程每0.5s随机生产一个0-10的数字,另一线程5s统计一次结果。 7 #生产者 8 class DataProducer(threading.Thread): 9     q=None10     def __init__(self,_queue):11         threading.Thread.__init__(self)12         self.q=_queue13     def run(self):14         while True:15             time.sleep(0.5)16             self.q.put(random.randint(0,10),True)17 18 #消费者19 class DataConsumer(threading.Thread):20     q=None21     def __init__(self,_queue):22         threading.Thread.__init__(self)23         self.q=_queue24     def run(self):25         while True:26             time.sleep(5)27             sum=028             while not self.q.empty():29                 #不会空肯定能够get到数据 不用阻塞也不会报empty错30                 sum=sum+self.q.get(False)31             print("sum:"+str(sum))32 33 que=Queue.Queue()34 dp=DataProducer(que)35 dp.start()36 37 dc=DataConsumer(que)38 dc.start()
View Code

 

转载于:https://www.cnblogs.com/DreamDrive/p/5931111.html

你可能感兴趣的文章
Luogu P3393 逃离僵尸岛
查看>>
Flatten Binary Tree to Linked List
查看>>
Edit Distance
查看>>
软件工程第一次作业补充
查看>>
N76E003---输入捕获
查看>>
poj 1094 Sorting It All Out(拓扑排序)
查看>>
acdream B - 郭式树 (水题 卡cin,cout, 卡LL)
查看>>
BMP图像格式
查看>>
python的匿名函数lambda解释及用法
查看>>
c#遍历Dictionary使用KeyValuePair
查看>>
defineProperties属性的运用==数据绑定
查看>>
关于 IOS 发布的点点滴滴记录(一)
查看>>
《EMCAScript6入门》读书笔记——14.Promise对象
查看>>
CSS——水平/垂直居中
查看>>
Eclipse连接mysql数据库jdbc下载(图文)
查看>>
Python中Selenium的使用方法
查看>>
三月23日测试Fiddler
查看>>
20171013_数据库新环境后期操作
查看>>
poj 1654 && poj 1675
查看>>
运维派 企业面试题1 监控MySQL主从同步是否异常
查看>>