数据库 :
from pymysql import *
class DB(object):
def __init__(self):
self.conn = connect(host='localhost', port=3306, database='python_test_1', user='root', password='mysql', charset='utf8')
self.cos = self.conn.cursor()
# self.num = self.cos.execute()
def __enter__(self):
return self.cos
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.commit()
self.conn.close()
self.cos.close()
with DB() as db:
num = db.execute("""insert into classes(name) values("python9") """)
socket 的with简化代码 :
# 导包
from socket import *
# 定义一个套接字的类
class sock(object):
# 把一些固定的语句放入init中
def __init__(self):
self.server_soc = socket(AF_INET, SOCK_STREAM)
self.server_soc.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.server_soc.bind(("",1314))
self.server_soc.listen(1024)
# 将需要返回的数据放入return
def __enter__(self):
self.client_soc, client_addr = self.server_soc.accept()
content = self.client_soc.recv(1024)
return content.decode("utf-8")
# 关闭套接字
def __exit__(self, exc_type, exc_val, exc_tb):
self.server_soc.close()
self.client_soc.close()
while True:
with sock() as soc:
print(soc)