面向对象

本文介绍了一个使用Python实现的面向对象编程示例,包括类的定义、构造函数、封装、继承和多态等概念。通过一个具体的PasswordTool类,演示了如何进行密码强度检查并保存到文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类的定义

class ClassName

__init__(self)构造函数:初始化对象的各属性

self代表类的实例

面向对象的特点

封装:

将数据及相关操作打包在一起

支持代码复用

继承:

子类借用父类的行为

避免重复操作,提升代码复用程度

定义class ClassName(SuperClassName)

多态

在不同情况下用一个函数名启用不同方法

灵活性

# -*- coding:utf-8
class FileTool:
    def __init__(self,pathFile):
        self.pathFile = pathFile
    def write_to_file(self,line):
        f = open (self.pathFile,'a')
        f.write(line)
        f.close()
    def read_from_data(self):
        f = open(self.pathFile,'r')
        lines = f.readlines()
        f.close()
        return lines
class PasswordTool:
    def __init__(self, password):
        self.password = password
        self.password_level = 0

    def isNumberLoop(self):
        for c in self.password:
            if c.isnumeric():
                return True
        return False

    def isPhal(self):
        for c in self.password:
            if c.isalpha():
                return True
        return False
    def process_Password(self):
        #规则一
        if len(self.password) >= 8:
            self.password_level += 1
        else:
            print("密码长度要求至少8位")
        #规则二
        if self.isNumberLoop():
            self.password_level+=1
        else:
            print("密码要求包含数字!")
        if self.isPhal():
            self.password_level += 1
        else:
            print("密码要求包含字母!")



def main():
    try_times = 5
    pathFile = 'password_6.0.txt'
    fileTool = FileTool(pathFile)
    while try_times >0:
        password = input("请输入密码")
        password_tool = PasswordTool(password)
        password_tool.process_Password()
        line = '密码:{},强度:{}\n'.format(password,password_tool.password_level)
        fileTool.write_to_file(line)
        if password_tool.password_level == 3:
            print("密码设置的不错o")
            break
        else:
            try_times -= 1
            print("密码很垃圾哦")
    lines = fileTool.read_from_data()
    for line in lines:
        print(line)


if(__name__ == '__main__'):
    main()


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值