将代码转换为python类

时间:2017-10-11 05:33:05

标签: python

我已经用简单的for循环编写了一个密码检查器的代码 - 现在我正在尝试使用Python类做同样的事情。

pwd = raw_input('Please enter the passowrd: ')

flag_upp = 0
flag_num = 0
flag_len = 0

for i in pwd:
    if(i.isupper()):
        flag_upp = 1
    if(i.isdigit()):
        flag_num = 1
if(len(pwd)>7):
    flag_len = 1

total_flag = flag_upp + flag_num + flag_len
flags = [flag_upp,flag_num,flag_len]
notations = ['Upper case missing','Number missing','Length must be minimum 8 chars']

if(total_flag==3):
    print 'Password is valid!'
else:
    print 'Invalid password!'
    for i in range(0,len(flags)):
        if(flags[i]==0):
            print notations[i]
        else:
            pass

如果我使用python类进行此操作应该是什么结构。

1 个答案:

答案 0 :(得分:1)

class password: 
    def __init__ (self, pwd): #Self is the automatic object
        self.pwd = pwd
        print 'password created'

    def validate(self):
        flag_upp = 0
        flag_num = 0
        flag_len = 0

        for i in self.pwd:
            if(i.isupper()):
                flag_upp = 1
            if(i.isdigit()):
                flag_num = 1
            if(len(self.pwd)>7):
                flag_len = 1

        total_flag = flag_upp + flag_num + flag_len
        flags = [flag_upp,flag_num,flag_len]
        notations = ['Upper case missing','Number missing','Length must be minimum 8 chars']

        if(total_flag==3):
            print 'Password is valid!'
        else:
            print 'Invalid password!'
            for i in range(0,len(flags)):
                if(flags[i]==0):
                    print notations[i]
            # else:
            #   pass

 D = str(raw_input('Password:'))
 p1 = password(D)
 p1.validate()