Python总结--基础知识-14

Python总结--基础知识-14

  • 1.信号量
  • 2.多线程下载图像文件
  • 3.自定义异常
  • 4.多继承
  • 5.异常处理

1.信号量

'''
信号量是一个计数器,用于记录资源的消耗情况。当资源消耗时递减,当资源
释放时递增。可以认为信号量代表资源是否可用
'''
from threading import BoundedSemaphore
MAX = 2
semaphore = BoundedSemaphore(MAX)
print(semaphore._value) #2
semaphore.acquire()
print(semaphore._value) #1
print(semaphore.acquire()) #True
print(semaphore._value) #0
print(semaphore.acquire(False))   # 如果没有资源可以申请(_value的值是0),再次调用acquire方法,会被阻塞
print(semaphore._value) #0
semaphore.release()  # 第一次释放资源
print(semaphore._value) #1
semaphore.release()  # 第二次释放资源
print(semaphore._value) #2
#semaphore.release()  # 第三次释放资源,现在已经没有资源被占用,所以会抛出异常
#print(semaphore._value) #2

2.多线程下载图像文件

from urllib3 import *
import threading
http = PoolManager()
disable_warnings()

f = open('urls.txt','r')
urlList = []
while True:
    url = f.readline()
    if url == '':
        break
    urlList.append(url.strip())
f.close()

print(urlList)

class DownloadThread(threading.Thread):
    def __init__(self,func,args):
        super().__init__(target=func,args=args)

def download(filename,url):
    response = http.request('GET',url)
    f = open(filename,'wb')
    f.write(response.data)
    f.close()
    print('<',url,'>','下载完成')

for i in range(len(urlList)):
    thread = DownloadThread(download,(str(i) + '.jpg',urlList[i]))
    thread.start()

3.自定义异常

'''
自定义异常类需要从Exception类继承,抛出异常类使用raise,捕捉异常类使用
try except语句。
'''
class MyException(Exception):
    pass

num = 50
try:
    if num >= 10:
        raise MyException('抛出异常')
    print('正常执行代码')
except MyException:
    print('发生了异常')

4.多继承

'''
支持多继承,如果多个父类存在冲突的成员,那么会使用最先遇到的成员
'''
class Calculator:
    def calculate(self,expression):
        self.value = eval(expression)
        return self.value
    def printResult(self):
        print('result:{}'.format(self.value))
class MyPrint:
    def print(self,msg):
        print('msg:',msg)
    def printResult(self):
        print('计算结果:{}'.format(self.value))
class MyCalculator1(Calculator,MyPrint):
    pass
class MyCalculator2(MyPrint,Calculator):
    pass

my1 = MyCalculator1()
print(my1.calculate("1+3 * 5")) #16
my1.print("hello") #msg: hello
my1.printResult() #result:16

my2 = MyCalculator2()
print(my2.calculate("3+5*3")) #18
my2.printResult() #计算结果:18

5.异常处理

'''
try…except…else语句中的except子句中的代码会在发生异常时执行,而else
子句中的代码会在try…except之间的代码正常执行完后执行,也就是当代码
执行正确时执行
'''
while True:
    try:
        x = int(input('请输入x:'))
        y = int(input('请输入y:'))
        value = x / y
        print('x / y is',value)
    except Exception as e: # 发生异常时执行
        print('不正确的输入:',e)
        print('请重新输入')
    else:  # 未发生异常时执行
        break

温馨提示:
以上文章描述如有不清晰之处,欢迎在评论区评论,如有时间,会第一时间回复,谢谢!

你可能感兴趣的:(Python)