python基础
Posted 萌萌~哒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础相关的知识,希望对你有一定的参考价值。
一、私有
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)
以上是关于python基础的主要内容,如果未能解决你的问题,请参考以下文章