模块 import
导入模块是python最常用的一种便捷用法,python有各式各样的开源模块供使用,也可以自定义一个模块使用
import XXXXXXXXXX as x
from XXXXXXXXXX import X
面向对象
class Pople(): 定义一个类 首字母大写
def __init__(self,name,sex):
self.__name = name 将name定义为一个不可改变的变量 不能通过外部调用函数变量改变其值,需要类里内部函数做变更
self.sex = sex
def eat():
pass
class Zhangsan(Pople):
def __init__(self,name,sex,age,new) 或者使用super来初始化
self.name = name super().__init__(name) 将子类中的值放到父类中去初始化,
self.age = age
with的自定义
with中包含了 __enter__ 和 __exit__ 方法
class Testwith():
def __enter__(self):
print('enter')
def__exit__(self,exc_type,exc_val,exc_tb):
if exc_tb is None:
print(‘exit normal’)
else:
print(‘exit with exception’)
with Testwith(): 执行之前会先执行enter里面的逻辑 执行完之后会去执行exit的逻辑 如果有异常 可以通过exc捕获
print(‘test’)
raise NameError(‘Exception’)
多线程编程
最多线程是有两个原因决定的,内存容量和软件限制,虽然线程是轻量级进程,但是创建线程也是要消耗内存的,初始状态下消耗大小就是内存栈了,每创建一个线程为其分配一个线程栈,还有一种限制是系统的配置参数限制,比如在linux上每进程创建线程是1024个,在local_lim.h中定义,可以使用ulimt -a查看线程栈大小
不使用多线程的情况
def myThread (arg1,arg2):
print(‘%s %s’ %(arg1,arg2))
for i in range(1,6,1):
t1 = myThread(i , i+1)
使用多线程的情况:
import threading
from threading import current_thread
def myThread(arg1,arg2):
print(current_thread().getName(),'start') #显示当前线程的状态
print('%s,%s' %(arg1,arg2))
time.sleep(1)
print(current_thread().getName(),'stop')
for i in range(1,6,1):
t1 = threading.Thread(target=myThread,args=(i, i+1))
t1.start()
t1.join() 不调用jion方法,执行完子线程之前就会先把主线程执行完毕,
print(current_thread().getName(),'end')
多线程经典案例:生产者和消费者 创建一个队列。,使用线程进行生产数据到队列和消费队列中的数据
from threading import current_thread,Thread
import time
import random
from queue import Queue
queue = Queue(5) 创建一个长度为5的队列
class ProducerThread(Thread):
def run(self):
name = current_thread().getName() 获取线程名称
nums = range(100)
global queue
while Ture:
num = random.chose(nums)
queue.put(num) 往队列里写入数据
t = random.randint(1,3)
time.sleep(t)
class ConsumerThread(Thread):
def run (self):
name = current_thread().getName()
globle queue
while True:
num = queue.get()
queue.task_done()
t = random.andomint(1,5)
time.sleep(t)
p1 = ProducerThread(name = 'p1')
p1.run() 单独运行run方法,会把主进程当成一个线程来看,执行的代码空间在MainThread主线程中,
p1.start() 执行start方法,python会创建一个新线程,叫 Thread-1 然后再去调用run()来运行
c1 = ConsumerThread(nem = 'c1')
c1.start()