python关于类的笔记(判断密码强弱实例)

python关于类的笔记(判断密码强弱实例)

类的特点

python关于类的笔记(判断密码强弱实例)_第1张图片
运行结果
python关于类的笔记(判断密码强弱实例)_第2张图片
代码如下

class PasswordTool:
    '''
        密码工具类
    '''
    #__init__(self)构造函数:初始化对象的各属性,self代表类的实例
    #password是传入的数据
    def __init__(self,password):
        #self.password表示passwod附属于self的属性
        #类的属性
        self.password = password
        self.strength_level = 0
    #类的方法,只要是在类里面定义的函数都要加个self
    def number_exist(self):
        include_num = False
        for c in self.password:
            if c.isnumeric():
                include_num = True
            
        return include_num

    def str_exist(self):
        include_str = False
        for s in self.password:
            if s.isalpha():
                include_str = True
                break
        return include_str

    def process_password(self):
        if len(self.password)>8:
            self.strength_level +=1
        else:
            print('输入的密码长度不够')
        if self.number_exist():
            self.strength_level +=1
        else:
            print('输入的密码不含数字')
        if self.str_exist():
            self.strength_level +=1
        else:
            print('输入的密码不含字母')


class FileTool:
    def __init__(self,filepath):
        self.filepath = filepath

    def write_to_file(self,line):
        fp = open(self.filepath,'a')
        fp.write(line)
        fp.close()

    def read_from_file(self):
        f = open(self.filepath,'r')
        lines = f.readlines()
        f.close()
        return lines
    


def main():
    try_time = 5
    filepath = 'password_class.txt'
    #实例化文件工具对象
    file_tool = FileTool(filepath)
    while try_time>0:
        password = input('请输入密码:')

        #实例化密码工具对象
        password_tool = PasswordTool(password)
        password_tool.process_password()

        line = '密码为:{},密码强度为:{}级\n'.format(password,password_tool.strength_level)
        file_tool.write_to_file(line)        

       
        
        if password_tool.strength_level==3:
            print('恭喜密码合格!')
            break
        else:
            print('密码强度不合格!')
            try_time -=1

        print()

        if try_time <=0:
            print('尝试次数过多,密码设置失败!')

    print('密码强度为{}级,密码合格'.format(password_tool.strength_level))

    lines = file_tool.read_from_file()
    print(lines)
            


if __name__ == "__main__":

    main()
    

你可能感兴趣的:(python入门,python,类)