python基础(九)

时间:2021-10-30 20:00:06

一、私有

class DB:
port = 3306 #类变量
def __init__(self):
self.host = '127.0.0.1'
self.__user = 'root' #实例变量,成员变量
self.__password = '123456'
self.db = 'xx'
# self.__help()
def sql(self,sql):
self.__help()
print('执行sql')
def __help(self):
print(self.host)
print(self.__user)
print(self.__password)
print(self.db)
print(self.port) def get_port(self): #实例方法
print(self.port) @classmethod
def help(cls):
print('这个类是用来连接数据库的,它的用法是xxx')
print('cls的内存地址',id(cls)) DB.help() 二、多线程及多线程下载网页
import threading
import time
def run():
time.sleep(5)
print('over') start_time = time.time()
for i in range(100):
t = threading.Thread(target=run)
t.start() print('运行的时候几个线程',threading.activeCount() ) # 1
#threading.activeCount就是当前有几个线程
while 1:
if threading.active_count()==1:
break print('这时候几个线程',threading.activeCount()) # 2
end_time = time.time()
print('run time =',end_time - start_time) # print('运行结束') ''' 第一种for循环主线程等待子线程运行结束
start_time = time.time()
ths = [] #100
for i in range(100):
t = threading.Thread(target=run) #实例化一个线程,
t.start()#启动这个线程
ths.append(t) for t in ths:
t.join() #循环等待每个子线程执行结束
end_time = time.time()
print('run time =',end_time - start_time)
''' # start_time = time.time()
# run()
# run()
# run()
# run()
# end_time = time.time()
# print('run time =',end_time - start_time)
import requests
import time
import threading
def download_html(url,file_name):
res = requests.get(url)
with open(file_name+'.html','wb') as fw:
fw.write(res.content)
print('【%s】下载完成'%file_name) urls={
'nnzhp':'http://www.nnzhp.cn',
'cc':'http://www.cc-na.cn',
'dsx':'http://www.imdsx.cn',
'besttest':'http://www.besttest.cn',
} start_time = time.time() for file_name,url in urls.items():
t = threading.Thread(target=download_html,args=(url,file_name))
#args=(url,) #单个参数的时候,一定要这么写
t.start()
while threading.active_count()!=1:
pass end_time = time.time()
print('run time =',end_time - start_time) #单线程
# start_time = time.time()
# for k,v in urls.items():
# download_html(url=v,file_name=k)
# end_time = time.time()
# print('run time =',end_time - start_time) 三、静态方法及守护线程
import turtle as t
import time
class Pig:
words = '老铁们,爱你们'
@classmethod
def pq(cls):
t.pensize(4)
t.hideturtle()
t.colormode(255)
t.color((255, 155, 192), "pink")
t.setup(840, 500)
t.speed(0.5) # 鼻子
t.pu()
t.goto(-100, 100)
t.pd()
t.seth(-30)
t.begin_fill()
a = 0.4
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a = a + 0.08
t.lt(3) # 向左转3度
t.fd(a) # 向前走a的步长
else:
a = a - 0.08
t.lt(3)
t.fd(a)
t.end_fill() t.pu()
t.seth(90)
t.fd(25)
t.seth(0)
t.fd(10)
t.pd()
t.pencolor(255, 155, 192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45)
t.end_fill() t.pu()
t.seth(0)
t.fd(20)
t.pd()
t.pencolor(255, 155, 192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45)
t.end_fill() # 头
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(41)
t.seth(0)
t.fd(0)
t.pd()
t.begin_fill()
t.seth(180)
t.circle(300, -30)
t.circle(100, -60)
t.circle(80, -100)
t.circle(150, -20)
t.circle(60, -95)
t.seth(161)
t.circle(-300, 15)
t.pu()
t.goto(-100, 100)
t.pd()
t.seth(-30)
a = 0.4
for i in range(60):
if 0 <= i < 30 or 60 <= i < 90:
a = a + 0.08
t.lt(3) # 向左转3度
t.fd(a) # 向前走a的步长
else:
a = a - 0.08
t.lt(3)
t.fd(a)
t.end_fill() # 耳朵
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(-7)
t.seth(0)
t.fd(70)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 54)
t.end_fill() t.pu()
t.seth(90)
t.fd(-12)
t.seth(0)
t.fd(30)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 56)
t.end_fill() # 眼睛
t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-95)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill() t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill() t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-25)
t.seth(0)
t.fd(40)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill() t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill() # 腮
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-95)
t.seth(0)
t.fd(65)
t.pd()
t.begin_fill()
t.circle(30)
t.end_fill() # 嘴
t.color(239, 69, 19)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(-100)
t.pd()
t.seth(-80)
t.circle(30, 40)
t.circle(40, 80) # 身体
t.color("red", (255, 99, 71))
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100, 10)
t.circle(300, 30)
t.seth(0)
t.fd(230)
t.seth(90)
t.circle(300, 30)
t.circle(100, 3)
t.color((255, 155, 192), (255, 100, 100))
t.seth(-135)
t.circle(-80, 63)
t.circle(-150, 24)
t.end_fill() # 手
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-40)
t.seth(0)
t.fd(-27)
t.pd()
t.seth(-160)
t.circle(300, 15)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-10)
t.circle(-20, 90) t.pu()
t.seth(90)
t.fd(30)
t.seth(0)
t.fd(237)
t.pd()
t.seth(-20)
t.circle(-300, 15)
t.pu()
t.seth(90)
t.fd(20)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-170)
t.circle(20, 90) # 脚
t.pensize(10)
t.color((240, 128, 128))
t.pu()
t.seth(90)
t.fd(-75)
t.seth(0)
t.fd(-180)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20) t.pensize(10)
t.color((240, 128, 128))
t.pu()
t.seth(90)
t.fd(40)
t.seth(0)
t.fd(90)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20) # 尾巴
t.pensize(4)
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(70)
t.seth(0)
t.fd(95)
t.pd()
t.seth(0)
t.circle(70, 20)
t.circle(10, 330)
t.circle(70, 30)
t.up()
t.goto(180, 90)
t.pencolor('red')
t.write(cls.words, font=('微软雅黑', 15, 'normal'))
time.sleep(50)
@staticmethod
def about_me():
print('这个猪的类,可以画佩奇 Pig.pq() \n'
'还可以画乔治 ,pig,qz()') Pig.words = '哈哈哈哈哈,一个精致的猪猪女孩!'
Pig.about_me() 修改父类的方法
class Lw:
def about_me(self,name):
print('[%s] 会抽烟喝酒烫头'%name)
print('[%s] 会抽烟喝酒烫头'%name)
print('[%s] 会抽烟喝酒烫头'%name)
print('[%s] 会抽烟喝酒烫头'%name) class Xw(Lw):
def about_me(self,name,age):
super().about_me(name) #spuer指的就父类
print('age',age) def abc(self):
pass wxm = Xw()
wxm.about_me('王小明',18) 接口
import requests
import nnlog
class MyRequest:
log_file_name = 'MyRequest.log'#日子文件名
time_out = 10 #请求超时时间
def __init__(self,url,data=None,headers=None,file=None):
self.url = url
self.data = data
self.headers = headers
self.file = file
def post(self):
try:
req = requests.post(self.url,data=self.data,headers=self.headers,
files=self.file,timeout=self.time_out)
except Exception as e:
res = {"status":0,"err_msg":e.args} #0代表请求失败
else:
try:
res = {"status":1,"data":req.json()} #1代表返回的json
except Exception as e:
res = {"staus":2,"data":req.text} #2代表返回不是json
log_str = 'url: %s 请求方式:post data:%s ,返回数据:%s'%(self.url,self.data,res)
self.write_log(log_str)
return res def get(self):
try:
req = requests.get(self.url,params=self.data,headers=self.headers,timeout=self.time_out)
except Exception as e:
res = {"status":0,"err_msg":e.args} #0代表请求失败
else:
try:
res = {"status":1,"data":req.json()} #1代表返回的json except Exception as e:
res = {"staus":2,"data":req.text} #2代表返回不是json
log_str = 'url: %s get请求 data:%s ,返回数据:%s'%(self.url,self.data,res)
self.write_log(log_str)
return res @classmethod
def write_log(cls,content):
log = nnlog.Logger(cls.log_file_name)
log.debug(content) 四、继承
import threading
import time class MyThread(threading.Thread):
def run(self):
#这个方法必须叫run
time.sleep(5)
print('run..') for i in range(5):
t = MyThread()
t.start()
获取多线程运行函数的返回值
import requests
import threading all_res = []
def get_name(name):
r = requests.get('http://api.nnzhp.cn/api/user/stu_info',
params={'stu_name':name})
res = r.json()
all_res.append(res) for i in range(10):
t = threading.Thread(target=get_name,args=(i,))
t.start() while threading.active_count()!=1:
pass print(all_res) 守护线程
import threading
import time def hhh():
time.sleep(5)
print('hhhh') for i in range(100):
t = threading.Thread(target=hhh)
t.setDaemon(True) #设置子线程为守护线程
t.start() print('秦始皇死了') 锁
#coding=utf-8
import threading
num = 0
lock = threading.Lock() #申请一把锁
def xiaojun():
global num
# lock.acquire() #加锁
# num+=1
# lock.release() #解锁
# with lock: #和上面一样
# num += 1
num +=1
for i in range(1000):
t = threading.Thread(target=xiaojun)
t.start()
while threading.active_count()!=1:
pass
print(num)
#多个线程同时操作同一个数据的时候一定要加锁 多进程
from multiprocessing import Process
import multiprocessing
import time
import threading
def run_thread():
time.sleep(60)
print('%s在运行'%threading.current_thread()) def run():
for i in range(10):
t = threading.Thread(target=run_thread)
t.start()
while threading.active_count()!=1:
pass for i in range(10):
p = Process(target=run) #起进程
p.start()
p.pid 单元测试
#unittest
#junit
#phpunit
import unittest def calc(a,b):
return a+b class MyTest(unittest.TestCase):
def testa(self):
res = calc(1,2)
self.assertEqual(3,res,msg='预期结果和实际结果不一致')
def testb(self):
res = calc(0,1)
self.assertEqual(2,res,msg='预期结果和实际结果不一致') # unittest.main()