python基础代码(持续更新)
函数
1.装饰器通用结构
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def wrapper(fn):#第2步执行wrapper函数,此时fn=func def inner(*args, **kwargs):#第5步,执行inner函数 print('被装饰函数执行前装饰内容')#第6步 ret1 = fn(*args, **kwargs)#第7步,调用fn函数,因第2步中fn已被赋值为func,即结果调用的是func函数 print('被装饰函数执行后装饰内容')#第11步 return 'inner:',ret1#第12步inner函数执行完,将'inner:', '返回值'返回给第4步中的ret2 return inner#第3步,返回给调用者wrapper(func)返回值inner函数名,即最终赋值给第1步中的func变量 @wrapper #@wrapper相当于func = wrapper(func)第1步调用wrapper函数并传参func def func():#第8步,执行被修饰的func函数 print('被装饰函数')#第9步 return '返回值'#地10步,被修饰的func函数执行完,将'返回值'返回给第7步的ret1 ret2 = func()#第4步,调用func函数,因此时func已被赋值为inner,即最终是调用的inner函数 print(ret2)#最后一步 '''函数执行的结果一次是: >>被装饰函数执行前装饰内容 >>被装饰函数 >>被装饰函数执行后装饰内容 >>('inner:', '返回值') '''
操作系统、进程、线程、协程
1、用面向对象创建线程的方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#1.基础方法 from threading import Thread class MyThread(Thread): def __init__(self, args): super().__init__()#执行父类的init方法来给线程的创建提供基础的初始化支持 self.args = args def run(self):#子线程要干的活放在run方法中 print('in my thread:',self.args) print('main') t = MyThread('wahaha')#将wahaha参数传给args t.start() #助于理解版本 from threading import Thread, get_ident class MyThread(Thread): def __init__(self, args): super().__init__()#执行父类的init方法来给线程的创建提供基础的初始化支持 self.args = args print('init:', get_ident()) def run(self):#子线程要干的活放在run方法中 print('in my thread:',self.args) print('run:', get_ident()) print('main:', get_ident()) t = MyThread('wahaha')#将wahaha参数传给args t.start()
2.socket tcp协议传输基础版
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#server服务器端 import socket sk = socket.socket()#创建一个socket对象 sk.bind(('127.0.0.1', 9090))#给对象绑定一个地址 sk.listen()#监听 conn, addr = sk.accept()#等待客户端连接 msg_r = conn.recv(1024)#接收客户端发来的信息 print(msg_r.decode('utf-8')) conn.send(b'hello')#向客户端发信息 conn.close()#关闭这个客户端的连接 sk.close()#关闭服务端对外连接 #client客户端 import socket sk = socket.socket()#创建一个socket对象 sk.connect(('127.0.0.1', 9090))#连接服务端 sk.send(b'how are you')#向服务端发送信息 print(sk.recv(1024).decode('utf-8'))#接收服务端的信息
3.回调函数(利用进程池知识点)
回调函数 : Pool这个类中 回调函数是主进程执行
如果有两个任务,我的第二个任务在第一个任务执行完毕之后能够立即被主进程执行
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import os import time import random from multiprocessing import Pool def wahaha(num): time.sleep(random.random()) print('pid:',os.getpid()) return num def back(arg): print('call_back:',os.getpid(),arg) if __name__ == '__main__': print('主函数:',os.getpid()) p = Pool(5) for i in range(12): ret = p.apply_async(func=wahaha,args=(i,), callback=back) p.close() p.join()
4.生产者与消费者模型(运用Queue队列知识)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import time import random from multiprocessing import Process,Queue def consumer(q,name): while True: food = q.get() if food == 'stop':break print('%s 吃了 %s'%(name,food)) time.sleep(random.random()) def producer(q,name,food,n=10): for i in range(n): time.sleep(random.random()) fd = food+str(i) print('%s 生产了 %s'%(name,fd)) q.put(fd) if __name__ == '__main__': q = Queue(10) c1 = Process(target=consumer,args=(q,'alex')) c1.start() c2 = Process(target=consumer, args=(q, 'alex')) c2.start() p1 = Process(target=producer,args=(q,'太白','泔水')) p1.start() p2 = Process(target=producer, args=(q, 'egon', '鱼刺')) p2.start() p1.join() p2.join() q.put('stop') q.put('stop')
5.查票抢票(利用Lock锁的知识)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import json import time from multiprocessing import Lock from multiprocessing import Process def search(i): with open('db','r') as f:count_dic = json.load(f) time.sleep(0.2) print('person %s 余票 : %s张'%(i,count_dic['count'])) def buy(i): with open('db','r') as f:count_dic = json.load(f) time.sleep(0.2) if count_dic['count'] > 0: count_dic['count'] -= 1 print('person %s 购票成功'%i) time.sleep(0.2) with open('db','w') as f:json.dump(count_dic,f) def task(i,lock): search(i) lock.acquire() # 如果之前已经被acquire了 且 没有被release 那么进程会在这里阻塞 buy(i) lock.release() if __name__ == '__main__': lock = Lock() for i in range(10): p = Process(target=task,args=(i,lock)) p.start()
6.协程起socket(tcp协议)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#server端 import socket import gevent from gevent import monkey; monkey.patch_all() def talk(conn): while True: conn.send(b'hello') print(conn.recv(1024)) sk = socket.socket() sk.bind(('127.0.0.1', 9090)) sk.listen() while True: conn, addr = sk.accept() g = gevent.spawn(talk,conn) #client端 import socket from threading import Thread def client(): sk = socket.socket() sk.connect(('127.0.0.1',9090)) while True: print(sk.recv(1024)) sk.send(b'bye') for i in range(500): Thread(target=client).start()
7.socketserver并发编程
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#server端 import socketserver class MySocket(socketserver.BaseRequestHandler): def handle(self): conn = self.request addr = self.client_address while True: conn.send(b'hello') print(addr,conn.recv(1024)) if __name__ == '__main__': tcp_server = socketserver.ThreadingTCPServer(('127.0.0.1',9090),MySocket) tcp_server.serve_forever() #client端 import socket sk = socket.socket() sk.connect(('127.0.0.1',9090)) while True: print(sk.recv(5)) sk.send(b'byebye')