Python的听课笔记案例6--判别密码强度6.0
原创6.0 使用类封装与文件相关的操作
巩固面向对象编程,为涉及文件操作的方法定义一个文件工具类。
"""
作者:lanxingbudui
版本:6.0
日期:2019-08-03
功能:确定密码强度
2.0新功能:限制密码身份验证次数并终止周期
3.0新功能:将密码及其强度保存到文件中
4.0新功能:读取文件中的密码
5.0新增:定义password工具类
6.0新增:定义文件工具类
"""
class PasswordTool:
"""
加密工具类
"""
def __init__(self, password):
# 类的属性
self.password = password
self.strength_level = 0
# 类的方法
def process_string(self): # 处理字符串的方法。
# 规则1:密码长度较长8位
if len(self.password) >= 8:
self.strength_level += 1
else:
print(密码长度必须大于8位)
# 规则2:密码包含数字
if self.check_number_str():
self.strength_level += 1
else:
print(密码要求包括数字!)
# 规则3:密码包含字母
if self.check_letter_str():
self.strength_level += 1
else:
print(密码要求包括字母!)
def check_number_str(self):
"""
确定字符串是否包含数字。
"""
has_number = False
for c in self.password:
if c.isnumeric():
has_number = True
break
return has_number
def check_letter_str(self):
"""
确定字符串是否包含字母
"""
has_letter = False
for c in self.password:
if c.isalpha():
has_letter = True
break
return has_letter
class FileTool:
"""
文件工具类
"""
def __init__(self, file_path):
self.file_path = file_path
# 如何编写文件
def write_to_file(self, line):
f = open(self.file_path, a)
f.write(line)
f.close()
# 读取文件的方法。
def read_from_file(self):
f = open(self.file_path, r)
lines = f.readlines()
f.close()
return lines
def main():
"""
主函数
"""
try_times = 5
file_path = password_6.0.txt
# 实例化文件工具类对象
file_tool = FileTool(file_path)
while try_times >= 0:
password = input(请输入密码:)
# 实例化密码工具对象。
password_tool = PasswordTool(password)
password_tool.process_string()
# 写文件操作
line = 密码:{},强度:{}
.format(password, password_tool.strength_level) file_tool.write_to_file(line)
if password_tool.strength_level == 3:
print(祝贺你!密码强度合格!)
break
else:
print(密码强度不合格!)
try_times -= 1
print()
if try_times <= 0:
print(密码尝试次数过多,请重置!)
# 读文件操作
lines = file_tool.read_from_file()
print(lines)
if __name__ == __main__:
main()
主要知识点:
1、封装
将数据和相关操作打包在一起
支持代码重用
2、继承
子类(subclass)借用父类(superclass)的行为
避免重复操作,提高代码重用性。
定义class ClassName(SuperClassName)
3、多态
在不同情况下启用同一函数名的不同方法
灵活性
确定密码强度大小写的内容:

版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123



