其他分享
首页 > 其他分享> > 19.5.15笔记and作业

19.5.15笔记and作业

作者:互联网

装饰器

def A(func):
    def haha():
        print('哈哈')
        func()
        print('呵呵')
    return haha
@A
def hanshu():
    print('嘿嘿')
hanshu()

多态

class Dog():
    def jiao(self):
        print('汪汪')
class Cat():
    def jiao(self):
        print('喵喵')
def jiao(x):
    x.jiao()
d=Dog()
c=Cat()
jiao(d)
jiao(c)

推导式

lb=[i for i in range(1,100) if i%3==0 or i%7==0]
print(lb)

生成器

def gens():
    for i in range(1,100):
        if i % 3 == 0 or i % 7 == 0:
            yield i
a=gens()
for x in a:
    print(x)

生成器表达式

a=(i for i in range(1,100) if i%3==0 or i%7==0)
for x in a :
    print(x)

用迭代器写一个斐波那契

class Feibo():
    def __init__(self,num):
        self.num=num
        self.a=1
        self.b=1
        self.current=1
    def __iter__(self):
        return self
    def __next__(self):
        if self.current<=self.num:
            r=self.a
            self.a,self.b=self.b,self.a+self.b
            self.current+=1
            return r
        else:
            raise StopIteration
a=Feibo(5)
for x in a:
    print(x)

单例模式

class Single():
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'xx'):
            cls.xx=object.__new__(cls)
        return cls.xx
    def __init__(self,name):
        self.name=name
a=Single('张三')
b=Single('李四')
print(a==b)
print(a is b)
print(a.name)

property方法

class Yuan():
    def __init__(self,r):
        self.r=r
    @property
    def minaji(self):
        return self.r*3.14*2
    @property
    def zhouchang(self):
        return self.r*self.r*3.14
c=Yuan(5)
print(c.minaji)
print(c.zhouchang)

画一个四行五列的空心矩形

i=1
while i<=4:
    j=1
    while j<=5:
        if i==1 or i==4 or j==1 or j==5:
            print('*',end='')
        else:
            print(' ',end='')
        j+=1
    print()
    i+=1

hash的使用

class A():
    def __init__(self,name):
        self.name=name
    def __eq__(self, other):
        return self.name==other.name
    def __hash__(self):
        return hash(self.name)

a=A('张三')
b=A('张三')
c=A('李四')
print(a==b)
print(a is b)
d={a,b,c}
for x in d:
    print(x.name)

d多进程

from  multiprocessing import Process
import time
def changge():
    for x in range(10):
        print('唱歌',x)
        time.sleep(1)
def tiaowu():
    for x in range(10):
        print('跳舞',x)
        time.sleep(1)
if __name__ == '__main__':
    p1=Process(target=changge)
    p2=Process(target=tiaowu)
    p1.start()
    p2.start()
    print('结束')

为什么是先执行进程2的?

from  multiprocessing import Process
import  time
a=1
def hs1():
    global a
    a+=2
    print('进程hs1',a)
def hs2():
    global a
    a+=3
        print('进程hs2',a)

if __name__ == '__main__':
    p=Process(target=hs1)
    p2=Process(target=hs2)
    x=input('输入1')
    p.start()
    p2.start()
    print('主进程',a)

进程之间的通讯

from  multiprocessing import Process,Queue
q=Queue(4)#3表示只能存放三个数据
print(q.qsize())
q.put('消息1')
print(q.qsize())
q.put('消息2')
q.put('消息3')
print(q.qsize())
print('呵呵')
q.put('消息4')
print('hello')
print(q.qsize(),q.full())#qsize检测q的个数,qfull,检测qsize是否满了

from multiprocessing import Process,Queue

q=Queue(4)#3表示只能存放三个数据
q.put('消息1')
q.put('消息2')
q.put('消息3')
q.put('消息4')

print(q.empty())#判断是否为空,不为空,因为还没有被取出
 print(q.get())#获取消息1
 print(q.get())#获取消息2
 print(q.get())#获取消息3
print(q.get())#获取消息4
while q.qsize()>0:
    print(q.get())
print(q.empty())#为空,因为上面get已经都拿出去了

from multiprocessing import Process,Queue

def hanshu1(a,b):
    print('进程1',a+b)
def hanshu2(name):
    print(name,'处理进程')
if __name__ == '__main__':
    p1=Process(target=hanshu1,args=(2,3))
    p2 = Process(target=hanshu2, args=('张三',))##括号内是元祖,如果没有逗号,则是字符串了,会报错
    p1.start()
    p2.start()

from multiprocessing import Process,Queue

q=Queue(3)#3表示只能存放三个数据
q.put('消息1')
q.put('消息2')
q.put('消息3')
try:
    q.put('消息4',timeout=3,block=False)#block为False时,不阻止
except:
    print('满了')
print(q.get())
print(q.get())
print(q.get())

try:
    print(q.get(timeout=2,block=True))#block为True时阻止
except:
    print('消息队列空了')
print('结束了')

from multiprocessing import Process,Queue

import time
def shengchan(q,name):
    for i in range(10):
        a='%s包子%d'%(name,i+1)
        print('生产',a)
        q.put(a)
        time.sleep(1)
def xiaofei(q):
    while True:
        try:
            a=q.get(timeout=2)
            print('吃:',a)
        except:
            break

if __name__ == '__main__':
    q=Queue(3)
    p1=Process(target=shengchan,args=(q,'张三'))
    p2=Process(target=xiaofei,args=(q,))
    p3 = Process(target=shengchan, args=(q, '李四'))
    p1.start()
    p2.start()
    p3.start()

进程池

from  multiprocessing import Process,Queue,Pool
import time
def jc(name):
    for i in range(10):
        print(name, '进程开始',i)
        time.sleep(1)
if __name__ == '__main__':
    p=Pool(7)
    for i in range(10):
        p.apply_async(jc,(i+1,))
        print('呵呵')
    p.close()
    p.join()

from multiprocessing import Process,Queue,Pool

import time
def downLoad(name):
    for i in range(5):
        print(name,'电影下载%.2f%%'%((i/4)*100))
        time.sleep(1)
    return name
def alert(name):
    print(name,'下载完成了')
if __name__ == '__main__':
    p=Pool(3)#控制进程池数
    a=['功夫熊猫','叶问','复仇者联盟3','蜘蛛侠','少林寺传奇','龙再江湖']
    for x in a :
        p.apply_async(downLoad,(x,),callback=alert)#执行完后,返回alert
    p.close()
    p.join()

import time

from threading import Thread
import threading
a=10
def dance():
    global a
    print(threading.current_thread().getName())#获取当前线程名字
    print(threading.current_thread())
    for i in range(10):
        a+=1
        print('跳舞{}'.format(a))
        time.sleep(1)
def singing():
    global a
    for i in range(10):
        a+=1
        print('唱歌{}'.format(a))
        time.sleep(1)
if __name__ == '__main__':
    t1=Thread(target=dance,)
    t2=Thread(target=singing)#为什么这里不用‘,’
    # t1.setDaemon(True)##守护主线程,当主线程结束,则子线程结束,不管有没有执行完
    # t2.setDaemon(True)
    # print(t1.is_alive())##查看子线程是否存活,因为t1子线程还没开始,所以为False
    t1.setName('小狗')#设置线程名字
    t1.start()
    #print(threading.current_thread(),'主线程')
    # print(t1.is_alive())  ##查看子线程是否存活,因为t1子线程已经开始,所以为True
    # t1.join()#等待第一个进程结束,再进行第二个进程
    t2.start()
    # print(threading.enumerate())#列举当前所有线程的名字
    print(threading.active_count())#计数当前线程数
    # print('主进程结束')
    # print(t1.is_alive())  ##查看子线程是否存活,因为t1子线程已经结束,所以为False

使用继承方开启线程

import time
from threading import   Thread
import threading
class MyThread(Thread):
    def __init__(self,num):
        super().__init__()
        self.num=num
    def ren(self):
        for x in range(self.num):
            print(x,'呵呵')
            time.sleep(1)
if __name__ == '__main__':
    t1=MyThread(5)
    t1.start()
    print(threading.enumerate())

共享全局变量问题

import time
from threading import Thread
import threading
g_num=0
def xian1():
    global g_num
    for i in range(1000000):
        g_num += 1
    print('1----',g_num,'#')
def xian2():
    global g_num
    for i in range(100000):
        g_num += 1
    print('2----',g_num,'#')
if __name__ == '__main__':
    t1=Thread(target=xian1)
    t2=Thread(target=xian2)
    t1.start()
    t2.start()
    print(g_num)

from multiprocessing import Process,Queue

import threading
import multiprocessing
from threading import Thread
def aa(q):#aa子进程
    q.put([1,2,3])
def a(q):#a进程
    a1=Thread(target=aa,args=(q,))
    a1.start()
    a1.join()
def bb(q):##bb子进程
    print(q.get())
def b(q):#b进程
    b1=Thread(target=bb,args=(q,))
    b1.start()
    b1.join()
if __name__ == '__main__':
    q=Queue(3)
    p1=Process(target=a,args=(q,))
    p2 = Process(target=b, args=(q,))
    p1.start()
    p2.start()

笔记
“”"
创建两个进程:进程A和进程B,用jcq消息队列实现他们的通信。
1、进程A里创建两个线程:线程A1 、线程A2.
在线程A1里创建一个a列表 [1,2,3,4,5,6], 用消息队列传递给线程A2,线程A2.
对列表进行筛选,删除掉奇数。然后用jcq消息队列发送给进程B
2、在进程B里创建两个线程:线程B1、线程B2
线程B2.接受进程A发过来的数据,并把这些数据,原封不动的用线程消息队列传递给线程B1
线程B1求出所有数的和并打印结果
“”"

from multiprocessing import Process, Queue, Lock
from threading import Thread
import queue
def JcA(q):
    a = [1, 2, 3, 4, 5, 6]
    qa = queue.Queue(6)#设置a的队列
    Xc_A1 = Thread(target=XcA1, args=(qa, a))#线程A1
    Xc_A2 = Thread(target=XcA2, args=(qa, a, q))#线程A2
    Xc_A1.start()#
    Xc_A2.start()
    Xc_A1.join()#主进程等待所有程序执行完成
    Xc_A2.join()
    pass
def XcA1(qa, a):
    for i in a:
        qa.put(i)#放a列表中的元素进入qa的队列
def XcA2(qa, a, q):
    b = []
    for i in range(len(a)):
        b.append(qa.get())#获取
    for j in b:
        if j % 2 == 0:#删选
            q.put(j)
def JcB(q):
    qb = queue.Queue(6)
    Xc_B2 = Thread(target=XcB2, args=(q, qb))
    Xc_B1 = Thread(target=XcB1, args=(qb,))
    Xc_B2.start()
    Xc_B1.start()
    Xc_B2.join()
    Xc_B1.join()
    pass
def XcB1(qb):
    d = []
    for i in range(3):
        d.append(qb.get())
def XcB2(q, qb):
    c = []
    for i in range(3):
        c.append(q.get())
    for j in c:
        qb.put(j)
    print(c)
    print(sum(c))
if __name__ == '__main__':
    q = Queue(3)
    J_A = Process(target=JcA, args=(q,))
    J_B = Process(target=JcB, args=(q,))
    J_A.start()
    J_B.start()

标签:__,19.5,15,name,self,笔记,print,import,def
来源: https://blog.csdn.net/peter_fanxing/article/details/90245733