类
- 实现注册、登录
class User:
def __init__(self, username, pwd):
self.username = username
self.pwd = pwd
def __str__(self):
return "'username':{},'pwd':{}".format(self.username, self.pwd)
class DB:
"""
单例模式
"""
instance = None
def __new__(cls, *args, **kwargs):
if DB.instance is None:
DB.instance = super().__new__(cls)
return DB.instance
# 构造方法
def __init__(self):
# 私有__,名称改变,外界无法访问,单个_只能靠自觉
self._pool = []
def save_user(self, user):
"""
存储数据
:param user:
:return:
"""
self._pool.append(user)
def get_user_by_name(self, username):
"""
查找数据
:param username:
:return:
"""
for user in self._pool:
if username == user.username:
return user
return None
def get_all(self):
return self._pool
# db = DB()
# db1 = DB()
# print(db)
# print(db1)
# 打印出来的地址相同<__main__.DB object at 0x7f73ba87eb70>,
# 所以只有一个实例对象,用于数据库访问操作
class View:
def show_info(self, info):
opt = input(info)
return opt
def read_user_info(self):
username = input("请输入用户名(6-9):\n")
pwd = input("请输入密码(6-9):\n")
if len(username)< 6 or len(username)> 9:
print("用户名不合法")
return None
if len(pwd)< 6 or len(pwd)> 9:
print("密码不合法")
return None
return User(username, pwd)
def show_user_list(self, users):
for user in users:
print(user)
class Service:
def __init__(self):
self.db = DB()
def regiser(self, user):
exist_user = self.db.get_user_by_name(user.username)
if exist_user is not None:
return print("该用户以存在")
self.db.save_user(user)
print("注册成功")
def login(self, user):
exist_user = self.db.get_user_by_name(user.username)
if exist_user is None:
print("用或,密码错误")
if exist_user.pwd == user.pwd:
print("登陆成功\n")
return exist_user
def list(self):
return self.db.get_all()
class App:
def __init__(self):
self.v = View()
self.s = Service()
self.cur_user = None
def start(self):
while True:
view_opt = self.v.show_info("请选择要进行的操作:\n 1.注册 \n 2.登陆 \n 3.退出")
if view_opt == "1":
user = self.v.read_user_info()
if user is not None:
self.s.regiser(user)
if view_opt == "2":
user = self.v.read_user_info()
login_user = self.s.login(user)
if login_user is not None:
self.cur_user = login_user
self.show_home()
def show_home(self):
while True:
user_opt = self.v.show_info("请选择要进行的操作:\n 1.查看用户信息 \n 2.查看用户列表 \n 3.退出")
if user_opt == "1":
print(self.cur_user)
if user_opt == "2":
users = self.s.list()
self.v.show_user_list(users)
if user_opt == "3":
break
app = App()
app.start()
- 六一我要过节,吃棒棒糖
怎么过节呢
把我边上的suntong卖了换糖吃,让他给我干活,给我监控服务器
<_>模拟监控服务:观察者模式
Ps:每隔5s向某台服务器发送请求,看是否获取正常的返回,如果 返回正常,则继续监控,如果连续3次没有返回正常值,则向指定用户发送信 息通知
三台服务器, 向一堆人发送短信
import random
class Server:
def_init_(self,name):
self.times = random.randint(3,10)
self.name = name
def connect(self):
if self.times > o
self.times -= 1
return True
return False
class Monitor:
def_init_(self):
#监控列表
self.servers = []
self.admin = []
def add_server(self,server):
self.servers,append(server)
return self
def admin(self,admin)
self.admins, append(admin)
def test(self):
for server in self.servers:
if not server.connect():
#通知相关者
for admin in self.admin:
Advisor.send_sms(admin,server.name + "链接异常")
pass
else :
print(server,name + "测试正常...")
class Advision:
@staticmethod
def send_sms(admin,msg):
print('向' + admin + "发送信息" + msg)
monitor = Monitor()
monitor.add_admin("zs")
monitor.add_admin("lisi")
monitor.add_server(Server("server1")).add_server(Server("server2"))
import time
while True:
tongtong儿童节被打哭了呢
- 观察者模式
#设计模式:一种通用的解决方案
#观察者模式
class Observer:
"""
观察者
"""
def __init__(self):
pass
def update(self):
pass
class Subject:
def __init__(self):
self.observers = []
def add_observer(self,observer):
self.observers.append(observer):
def remove_observer(self,observer):
self.observers.remove(observer)
def notify(self):
for observer in self.observers:
observer.update('msg')
tongtong = Observer("tongtong")
lihua = Observer("lihua")
rain = Subject()
rain.add_observer(tongtong)
rain.add_observer(lihua)
rain.notify("彤彤哭了")
rain.remove_observer(lihua)
儿童节,彤彤的女朋友不开心了
但是他还不会处理异常
#异常处理
#获得原谅比获得许可更容易
#异常发生后,程序就结束了
#抛出了一个异常
'''
try:
opt = int(input("请输入一个整数"))
except :
print("你输入的不是一个数")
print(opt)
'''
'''
try:
opt = int(input("请输入一个整数"))
except ValueError as e:
print(e)
'''
#try:
#可能发生异常的代码
#except:处理所有异常
#except Type:处理指定类型的异常
#except Type as date:获取异常信息
#except (Type1,Type2,Type3):同时处理这三种异常,如果想获取这三种异常数据,同样可以使用as语句
student = {"name":"zs"}
try:
opt = int(input("请输入一个整数"))
print(student['age'])
except ValueError :
print('ssds')
print("hello")
'''
try:
pass
except 异常类型1:
pass
except 异常类型2:
pass
except (异常类型3,异常类型4,异常类型5):
pass
except Exception as e:
'''
#定义这种方式捕捉异常时,一定要先写具体的异常,再写具有普遍性的异常,所有的异常,继承自Exception
#try:
#except:
# 没有发生异常
#else:
# 没有发生异常时执行
#finally:
# 有没有异常都会执行
#可以只有try...finally语句
#finally一般用来释放资源
try:
print("zs")
finally:
print("finally")
try:
num = input("请输入整数")
result = 8 / num
print(result)
except ValueError:
print("请输入一个整数")
except ZeroDivisionError:
print("整数不能为0")
except Exception as e:
print("未知错误%s" % e)
else:
print("正常执行")
finally:
print("执行完毕....不保证正确")
#异常的传递,异常发生后,会传递给方法(函数)的调用者A如果A有捕捉到该异常,则按捕捉机制处理,如果未捕捉到该异常则会层层向上传递
#最终会传递到python解析器,此处就简单的终止程序
def fun1():
a = 0:
print(10 / a)
def fun2():
try:
fun1()
except ZeroDivisionError:
print("出错为0")
fun2()
#手动抛出异常
def fun3():
print("hello")
raise ZeroDivisionError()
fun3()
#自定义异常
class ParamInvalidExcption(Exception):
pass
def login(username,pwd):
if len(username) < 6:
raise ParamInvalidExcption("用户名长度在1-6位之间")
if username != "tongtong"
raise ParamInvalidExcption("用户名错误")
print("登陆成功")
try:
login()
print('tongtong',"12345")
print("后继操作")
except ParamInvalidExcption as e:
print(e)
#程序发生了异常怎么办?
#是否是可控的?不可控的话,不管它,可控的异常,进行处理,不管是否可控,都先记录下来
try:
pass
except Exception:
#先记录异常
#能处理就处理
#不能处理,raise
- 彤彤可真是地主家的傻儿子
字符问题
#字符问题
#如何表示字符map 65 ->a 66 ->b;ASCII一个字符占8bit,2**8=256 ==127个
#GB2312 #GBK
#Unicode 编码 16 2**16
#UTF-8 变长编码
bytes = '张三'.encode("GBK")
print(bytes)
print(type(bytes))
byte_utf8 = '张三'.encode("utf-8")
print(byte_utf8)
str = bytes.decode("GBK")
print(str)
str = byte_utf8.decode("GBK")
print(str)
文件操作
#文件操作
#文本文件 二进制文件
#文本文件本质上存储时也是二进制,但可以用文本编辑器查看
#二进制文件无法用文本编辑器查看
#写
f = open("D://demo.txt","w")
f.write(" neuedu\n")
f.write('NEUQ')
f.write("一片两片")
finally:
f.close()
with open("D://demo.txt",'w',encoding="utf-8") as ff:
ff.write(" neuedu\n")
ff.write('NEUQ')
ff.write("一片两片")
#读
#help(open)
with open("D://demo.txt") as f:
content = f.read()
print(content)
help(f.read())
with open("D://demo.txt", encoding="utf-8") as f:
#content = f.read()
#print(content)
#line = f.readline()
#while line:
# print(line)
# line = f.readline()
for line in f.readlines():
print(line)
with open("D://demo.txt", encoding="utf-8") as f:
print(f.read())
#whence:0:文件的开头;1:当前指针所在位置;2:文件的末尾
f.seek(0,0)
print(f.tell())
print(f.read())
#文件的打开模式:
#r:以只读方式打开文件,文件的指针会放在文件的开头,这是默认模式,如果文件不存在,抛出异常
#w:以只写的方式打开文件,如果存在,则覆盖文件,如果不存在,则创建文件
#a:以追加的方式打开文件,如果文件已存在,则指针会放在文件的结尾,如果不存在,则创建新文件
#r+;以读写的方式打开文件,文件的指针会放在文件的开头,如果文件不存在,抛出异常
#w+:以读写的方式打开文件,如果存在,则覆盖文件,如果不存在,则创建文件
#a+: 以读写的方式打开文件,如果存在,则指针会放在文件的结尾,如果不存在,则创建新文件
with open("D://1200.jpg",'rb') as f:
lines = f.read()
with open("D://1200.jpg",'rb') as f1:
f1.write(lines)
儿童节,我要去吃糖糖啦!
ps:作业
#作业:创建文件:doto.txt, 一共100000行,(1)每行存放一个1-100之间的整数
# (2)找出文件中出现最多的10个数字,写入到文件,mostNum.txt中, collection.Counter
from collections import Counter
count_list = Counter(['B','A','B','A','B','B','A','B','B','C'])
print(count_list)
print(count_list.most_common(2))
count_truple = Counter((1,2,3,1,1,1,2,1,3,3))
print(count_truple)
import random
with open("date.txt",'w+') as f:
for i in range(10000):
num = random.randint(1,101)
f.write(str(num)+ "\n")
with open("date.txt","r+") as f:
lists = []
line = f.readline()
while line:
lists.append(line)
line = f.readline()
print(Counter(lists),most_common(10))